鼠标移动跟随案例
js知识点:JavaScript事件

JavaScript事件知识点详见上一篇文章:https://blog.csdn.net/weixin_43969648/article/details/123296927?spm=1001.2014.3001.5502

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>案例:鼠标跟随</title>
    
    <style>
        img {
   
            width: 40px;
            height: 40px;
            position: fixed;
            left: 0;
            top: 0;
        }
    </style>
    
</head>
<body>
    //放置一张图片(图片放在下面)
    <img src="../static/img/2.png" alt="">

    <script>
        var imgBox = document.querySelector('img')

        //给document 绑定一个鼠标移动事件
        document.onmousemove = function (e) {
   
            //拿到光标相对于窗口的坐标位点
            var x = e.clientX
            var y = e.clientY

            //把 x 和 y 的值赋值给 img 标签的 left 和 top 样式
            imgBox.style.left = x + 5 + 'px'
            imgBox.style.top = y + 5 + 'px'
        }
        
    </script>

</body>
</html>

图片:

文章参考视频:b站千锋前端学习营:千锋前端JavaScript全套教程_JS零基础完美入门到项目实战https://www.bilibili.com/video/BV1W54y1J7Ed?share_source=copy_web