JS简单实现鼠标移动动画

效果图:

小图片会随着鼠标移动而移动

实现思路:

图片设置绝对定位,然后通过给 document 对象绑定 mousemove 事件,并且获取鼠标移动时的所在坐标,并把坐标的 XY 值赋给图片的 top 和 left 位置。赋值时,减去图片宽高的一半是为了调整图片相对于鼠标的位置。

代码:

<!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="../../../网页素材/小图标/angel.gif">
    <script>
        document.addEventListener('mousemove', function (e) {
            console.log(e.pageX, e.pageY);
            var img = document.querySelector('img');
            img.style.top = e.pageY - img.height / 2 + 'px';
            img.style.left = e.pageX - img.width / 2 + 'px';
        })
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_42207975/article/details/106501512