JS---案例:图片跟着鼠标飞的最终版本

案例:图片跟着鼠标飞的最终版本

换了个好看的糖果照片,想给博客首页加上,但是加上后,应该是overwrite原来的html,所以光有鼠标跟着飞的效果,原来的功能都不能用了

放入common.js 

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

<head>
  <meta charset="UTF-8">
  <title>title</title>

  <style>
    img {
      position: absolute;
    }
  </style>
</head>

<body>
  <img
    src="https://images.cnblogs.com/cnblogs_com/jane-panyiyun/1620008/t_191224122527%E5%9C%A3%E8%AF%9E%E7%B3%96%E6%9E%9C.png?a=1577190334776"
    alt="" id="im" />
  <script src="common.js"></script>
  <script>
    var evt = {
      //window.event和事件参数对象e的兼容
      getEvent: function (evt) {
        return window.event || evt;
      },
      //可视区域的横坐标的兼容代码
      getClientX: function (evt) {
        return this.getEvent(evt).clientX;
      },
      //可视区域的纵坐标的兼容代码
      getClientY: function (evt) {
        return this.getEvent(evt).clientY;
      },
      //页面向左卷曲出去的横坐标
      getScrollLeft: function () {
        return window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft || 0;
      },
      //页面向上卷曲出去的纵坐标
      getScrollTop: function () {
        return window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop || 0;
      },
      //相对于页面的横坐标(pageX或者是clientX+scrollLeft)
      getPageX: function (evt) {
        return this.getEvent(evt).pageX ? this.getEvent(evt).pageX : this.getClientX(evt) + this.getScrollLeft();
      },
      //相对于页面的纵坐标(pageY或者是clientY+scrollTop)
      getPageY: function (evt) {
        return this.getEvent(evt).pageY ? this.getEvent(evt).pageY : this.getClientY(evt) + this.getScrollTop();
      }
    };
    //最终的代码

    document.onmousemove = function (e) {
      my$("im").style.left = evt.getPageX(e) + "px";
      my$("im").style.top = evt.getPageY(e) + "px";
    };

  </script>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/jane-panyiyun/p/12093750.html