【问题标题】:Accessing variables with javascript (no jQuery) .onmouseup event使用 javascript(无 jQuery)访问变量 .onmouseup 事件
【发布时间】:2014-01-30 15:18:48
【问题描述】:

我在理解如何让变量在我的 .onmouseup 事件中工作时遇到了一些麻烦。

我有一个.onmousemove 事件,它定义了一个局部变量,例如鼠标自.onmousedown 以来移动的距离。我想在执行.onmouseup 的函数中使用该信息,但是,我无法获得它。以下是相关的代码:

document.onmousedown = function(){
   var mouseStart = [event.pageX,event.pageY];
   document.onmousemove = function(){
       var dist = Math.sqrt(Math.pow(event.pageY-mouseStart[1],2)+Math.pow(event.pageX-mouseStart[0],2));
       document.onmouseup = function() {
          global_function(dist);
          document.onmousemove = null;
      }
   }
}

我不明白为什么 mouseStart 可以访问,但我得到了 dist 未定义的错误。

我还有其他变量也需要传递,在.onmouseup 期间无法重新定义。

【问题讨论】:

  • 你为什么要绑定一个事件inside一个事件处理器inside一个事件处理器?
  • 在 Chrome 中运行良好 Fiddle

标签: javascript dom-events parameter-passing onmouseup


【解决方案1】:

我认为您需要在 onmousedown 处理程序中添加 onmouseup 事件处理程序。在某些浏览器中,mousemove 事件每秒触发 50 次,因此您反复添加和删除鼠标上/下事件。然后,您需要在 mousedown 处理程序中声明 dist

为了浏览器兼容性,event 对象在许多浏览器的事件处理程序中被传递,而在其他浏览器中它是一个全局变量。一个简单的event = window.event || event 加上向处理程序声明一个event 参数就可以解决问题。

document.onmousedown = function(event) {
    event = window.event || event;
    var mouseStart = [event.pageX,event.pageY];
    var dist;

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

    document.onmousemove = function(ev) {
        ev = window.event || ev;
        dist = Math.sqrt(Math.pow(ev.pageY-mouseStart[1],2)+Math.pow(ev.pageX-mouseStart[0],2));
    };
};

【讨论】:

    【解决方案2】:

    确保您的函数定义不会被动地从它们的闭包中继承 event 变量。您应该在函数定义中明确接受event 变量,即function(event){},而不是function(){}

    另外,你在 mousemove 事件中计算 dist 进行了过多的计算,它不应该在 mouseup 之前计算。

    以下内容在 Firefox 中适用于我。

    document.onmousedown = function(event){
        var mouseStart = [event.pageX,event.pageY];
        document.onmouseup = function(event) {
            var dist = Math.sqrt(Math.pow(event.pageY-mouseStart[1],2)+Math.pow(event.pageX-mouseStart[0],2));
            console.log(dist); //global_function(dist);
            document.onmouseup = null;
        }
    }
    

    【讨论】:

      【解决方案3】:

      我这样改了,效果很好:

      document.onmousedown = function (evt) {
          var e = evt || window.event;
          var mouseStart = [e.pageX, e.pageY];
          document.onmouseup = function (ev) {
              var evnt = ev || window.event;
              var dist = Math.sqrt(Math.pow(evnt.pageY - mouseStart[1], 2) + Math.pow(evnt.pageX - mouseStart[0], 2));
              alert(dist);
              document.onmouseup = null;
          };
      };
      

      如您所见,我已经删除了 onmousemove 事件,但它仍然可以得到相同的结果。

      【讨论】:

        猜你喜欢
        • 2011-01-29
        • 1970-01-01
        • 2017-09-07
        • 2011-11-23
        • 2016-12-04
        • 2017-11-21
        • 2023-03-17
        • 2010-11-28
        • 1970-01-01
        相关资源
        最近更新 更多