天使图片跟随鼠标移动案例

目标效果

在这里插入图片描述

代码实现

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>
<style>
  img {
    /* 为鼠标图片开启绝对定位,不占用文档流位置 */
    position: absolute;
  }
</style>

<body>
  <img src="./angel.gif" alt="">

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

    // 为document添加mousemove事件
    document.addEventListener('mousemove', function (e) {
      // 改变图片的top和left值,使其与pageY和pageX相等
      // pageX和pageY不带单位,需要用字符串补上
      myImg.style.top = e.pageY + 'px';
      myImg.style.left = e.pageX + 'px';
    });
  </script>
</body>

</html>
发布了114 篇原创文章 · 获赞 0 · 访问量 2547

猜你喜欢

转载自blog.csdn.net/qq_35764106/article/details/105154590