0
点赞
收藏
分享

微信扫一扫

JavaScript案例(四):鼠标移动跟随;html+css+js实现鼠标移动时小球跟随鼠标移动

史值拥 2022-03-11 阅读 72

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

<!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>

图片:
在这里插入图片描述

举报

相关推荐

0 条评论