JavaScript实现图片跟随鼠标效果

要求:

  1. 在浏览器页面中,图片实时跟随鼠标
  2. 鼠标在图片的中心位置

实现思路:

  1. 鼠标不断移动,使用鼠标移动事件:mousemove
  2. 在页面中移动,给document注册事件
  3. 图片要移动距离,而且不占位置,使用绝对定位即可
  4. 每次鼠标移动,获得最新的鼠标坐标,把这个xy坐标作为图片的topleft值就可以移动图片

代码实现:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        img {
            /* 因为图片不能影响页面其他的布局,所以用绝对定位 */
            position: absolute;
        }
    </style>
</head>

<body>
    <img src="https://img2020.cnblogs.com/blog/2171269/202010/2171269-20201010211141689-230895530.png" alt="">
    <script>
        var pic = document.querySelector('img');
        document.addEventListener('mousemove', function(e) {
            // 获取当前鼠标到页面的距离
            var x = e.pageX;
            var y = e.pageY;
            // 选用图片大小为50*50像素,让鼠标居中在它中间,x左移25px,y上移25px
            pic.style.left = x - 25 + 'px';
            pic.style.top = y - 25 + 'px';
        });
    </script>
</body>

</html>

实现效果:

将代码复制到记事本中,并改名为xx.html,保存。使用浏览器打开即可。

posted @ 2020-10-10 21:12  火星飞鸟  阅读(1457)  评论(0编辑  收藏  举报