处理" mousedown"不同对象上的事件

时间:2014-09-04 20:55:04

标签: javascript event-handling addeventlistener

我试图通过鼠标拖动来改变两个小节(div)的长度(在eloquetjavascript小册子chapter 14中扩展一个例子,其中涉及通过拖动鼠标来改变一个小节的长度。)预期的行为是单击任意栏,按住鼠标左键移动鼠标将改变该栏的长度。

这是我的实施(also available on JSfiddle

<script>
  var lastX; // Tracks the last observed mouse X position
  var rect1 = document.getElementById("bar1");
  var rect2 = document.getElementById("bar2");
  rect1.addEventListener("mousedown", function(){watchmousedown(rect1)});
  rect2.addEventListener("mousedown", function(){watchmousedown(rect2)});                      

  function watchmousedown(rec) {
    if (event.which == 1) {
      lastX = event.pageX;
      addEventListener("mousemove",function(){moved(rec)});
      event.preventDefault(); // Prevent selection
    } else {
    removeEventListener("mousedown", watchmousedown)}
  }

  function moved(rec) {
    if (event.which != 1) {
      removeEventListener("mousemove", moved);
    } else {
      var dist = event.pageX - lastX;
      var newWidth = Math.max(10, rec.offsetWidth + dist);
      rec.style.width = newWidth + "px";
      lastX = event.pageX;
    }
  }
</script>

问题是我只能更改发生第一次鼠标单击事件的栏的长度。我假设我没有正确处理mousedown事件(可能需要重置一些如何)。

我是javascript的新手,对编程风格的帮助也很感激。

谢谢!

1 个答案:

答案 0 :(得分:1)

rec.添加到addEventListener("mousemove", function () {,以便将事件侦听器绑定到您单击的rec而不是窗口。

function watchmousedown(rec) {
    if (event.which == 1) {
        lastX = event.pageX;
        rec.addEventListener("mousemove", function () {
            moved(rec)
        });
        event.preventDefault(); // Prevent selection
    } else {
        rec.removeEventListener("mousedown", watchmousedown)
    }
}

编辑:我有一些事件处理程序未正确清理。我不知道这是否是我的最终代码,但这更接近于我将如何做到:

var lastX; // Tracks the last observed mouse X position
var rect1 = document.getElementById("bar1");
var rect2 = document.getElementById("bar2");

var moveRect1 = function () {
    console.log(arguments);
    moved(rect1)
};
var moveRect2 = function() {
    console.log(arguments);
    moved(rect2);   
}
var watchRect1 = function () {
    console.log(arguments);
    watchmousedown(moveRect1)
};
var watchRect2 = function () {
    console.log(arguments);
    watchmousedown(moveRect2)
};

rect1.addEventListener("mousedown", watchRect1);
rect2.addEventListener("mousedown", watchRect2);

window.addEventListener("mouseup", function() {
   removeEventListener("mousemove", moveRect1); 
   removeEventListener("mousemove", moveRect2); 
});

function watchmousedown(moverec) {
    if (event.which == 1) {
        lastX = event.pageX;
        addEventListener("mousemove", moverec);
        event.preventDefault(); // Prevent selection
    }
}

function moved(rec) {
    if (event.which == 1) {
        var dist = event.pageX - lastX;
        var newWidth = Math.max(10, rec.offsetWidth + dist);
        rec.style.width = newWidth + "px";
        lastX = event.pageX;
    }
}

编辑:删除了一条没有做任何事情的行