图片跟随鼠标案例

示例代码:

<!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>
        img {
            position: absolute;
            top: 2px;
        }
    </style>
</head>

<body>
    <img src="img/111.jpg" alt="" style="height:40px;">
</body>
<script>
    var img = document.querySelector('img')
    document.addEventListener('mousemove', function (e) {
        // 1.mousemove只要我们鼠标移动1px 就会触发这个事件
        // console.log(1);
        // 2.核心原理:每次鼠标移动,我们都会或的最新的鼠标坐标,把这个x和y坐标作为图片的top和left值就就可以移动图片
        var x = e.pageX
        var y = e.pageY
        console.log(x, y);
        // 3.不要忘记给left和top添加px
        img.style.left = x + 'px'
        img.style.top = y + 'px'
    })
</script>

</html>

 

posted @ 2022-04-12 09:15  今天穿秋裤了吗  阅读(45)  评论(0)    收藏  举报