在javascript中使用mousemove事件附加mousedown?

时间:2015-01-26 16:36:54

标签: javascript events

如何使用mousemove事件附加mousedown事件,这在一个示例中有更好的解释:

      var mousemovemethod = function (e) {
            var oldx = 0;
            var direction = "down";
            x = this;
            x.addEventListener("mousemove", function(e){
                if (e.pageX < oldx) {
                    direction = "left"
                } else if (e.pageX > oldx) {
                    direction = "right"
                }
            });

            document.body.innerHTML = direction;

            oldx = e.pageX;

    }

    document.addEventListener('mousedown', mousemovemethod);

所以这段代码的作用是当我点击它时显示down,所以mousedown事件处理程序工作得很好,但是在按下时我希望能够向右或向左移动,显然替换{{ 1}} downleft

jsFiddle这里: http://jsfiddle.net/ft8pdup6/

2 个答案:

答案 0 :(得分:1)

你的代码很好,除了你忘了在设置左或右后更新html

var direction = "",
oldx = 0,
mousemovemethod = function (e) {
    var oldx = 0;
    var direction = "down";
    x = this;
    x.addEventListener("mousemove", function(e){
        if (e.pageX < oldx) {
            direction = "left"
        } else if (e.pageX > oldx) {
            direction = "right"
        }
        //You forgot to to this
        document.body.innerHTML = direction;
    });

    document.body.innerHTML = direction;

    oldx = e.pageX;

}

小提琴:http://jsfiddle.net/1qfg8xtw/

释放按钮后,您也无法删除该事件。我认为这是有意的(如果不是,那就不难解决)。

答案 1 :(得分:0)

我设法解决了这个问题,我想我应该在这里发布:

var oldX = 0;
var move = function(e){
    if(e.pageX < oldX){
        document.body.innerHTML = "left";
    }
    if(e.pageX > oldX){
       document.body.innerHTML = "right";
    }
     oldx = e.pageX;
}
var start = function(event){
    document.body.innerHTML = "down";
    document.addEventListener("mousemove", move, true);
};
document.addEventListener("mousedown", start, false);