js实现图片跟随鼠标移动效果

通过事件对象属性e.clientX / e.clientY(鼠标距离浏览器窗口左上角的距离),实现图片随鼠标一起移动的功能~

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        #pic{
            position: fixed;
        }
    </style>
    
</head>
<body>
    <img src="imgs/rose.png" id="pic" width="50px" height="30px">

    <script>
        var pic = document.getElementById("pic");
        //通过鼠标移动事件 给图片添加left 和 top的值
        // 给整个document文档添加鼠标移动事件
        document.onmousemove = function(e){
            e = e || window.event;
            pic.style.left = e.clientX + "px";
            pic.style.top = e.clientY + "px";
        }
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/dreamtown/p/14477466.html