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';
    }

    这样就可以完美解决了!

  • 相关阅读:
    401. Binary Watch
    46. Permutations
    61. Rotate List
    142. Linked List Cycle II
    86. Partition List
    234. Palindrome Linked List
    19. Remove Nth Node From End of List
    141. Linked List Cycle
    524. Longest Word in Dictionary through Deleting
    android ListView详解
  • 原文地址:https://www.cnblogs.com/shenwh/p/15629555.html
Copyright © 2011-2022 走看看