zoukankan      html  css  js  c++  java
  • 关于document.onmousemove报错Invalid or unexpected token问题

    今天在用原生js写一个自定义滚动条的移动事件出现了一个问题,场景是点击一个div并移动该div(id为scroll_box),去让超出固定高度的div的滚动条跟着移动,一般正常逻辑如下:

    let oScrollBox = document.getElementById('scroll_box');

    oScrollBox.onmousedown = function(e) {
      let event1 = e || event;
      let positionY = event1.clientY - this.offsetTop;
      document.onmousemove = function(ev) {
        let event2 = ev || event;
        var divY = event2.clientY - positionY;
        oScrollBox.style.top = divY + 'px';

      }

      document.onmouseup = function() {
        document.onmousemove = null;
      };
    }

    这个时候会报错,纳闷了很久,为啥不行嘞,后来发现document.onmousemove方法里的event2 =  ev || event;这里导致的错误,因为上面let event1 = e || event;里面已经使用了event变量,所以导致报错,解决方法就是将document.onmousemove写进一个单独的方法中,这样就可以避免变量重复问题,代码如下:

    oScrollBox.onmousedown = function(e) {
      let event1 = e || event;
      let positionY = event1.clientY - this.offsetTop;
      document.onmousemove = function(ev) {
        mouseMove(oScrollBox,ev,positionY);
      }
      document.onmouseup = function() {
        document.onmousemove = null;
      }
    };
    function mouseMove(obj,e,positionY) {
      let event2 = e || event;
      var divY = event2.clientY - positionY;
      obj.style.top = divY + 'px';
    }

    这样就可以完美解决了!

  • 相关阅读:
    c# DateTime 格式化输出字符串
    计算运行时长
    ubuntu helpers
    json.net omit member
    git 本地项目关联新repo
    c# DirectoryEntry LDAPS
    为视图或函数指定的列名比其定义中的列多
    Java反序列化漏洞学习笔记
    流量抓包
    软件安全策略-下
  • 原文地址:https://www.cnblogs.com/shenwh/p/15629555.html
Copyright © 2011-2022 走看看