JavaScript implements the picture following the mouse effect

Claim:

  1. In the browser page, the picture follows the mouse in real time
  2. The mouse is in the center of the picture

Realization ideas:

  1. The mouse is constantly moving, use the mouse movement event:mousemove
  2. Move in the page, documentregister for events
  3. The picture needs to move the distance, and does not occupy the position, use absolute positioning
  4. Every time the mouse moves, get the latest mouse coordinates, use this xand ycoordinates as the topsum of the leftpicture to move the picture

Code:

<!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="https://img-blog.csdnimg.cn/20201026075813798.png" alt="">
    <script>
        var pic = document.querySelector('img');
        document.addEventListener('mousemove', function(e) {
     
     
            // 获取当前鼠标到页面的距离
            var x = e.pageX;
            var y = e.pageY;
            // 选用图片大小为50*50像素,让鼠标居中在它中间,x左移25px,y上移25px
            pic.style.left = x - 25 + 'px';
            pic.style.top = y - 25 + 'px';
        });
    </script>
</body>

</html>

Realization effect:

Copy the code into Notepad, rename it xx.html, and save. Just use the browser to open it.

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/109270177