简体   繁体   English

在对象中时未触发Javascript mousemove事件

[英]Javascript mousemove event not triggered when in object

I hope your doing fine. 希望你一切都好。 Here's my problem : 这是我的问题:

This code works fine : 这段代码可以正常工作:

var imageMover = {
    mouseDown: function(e) {
        e.target.addEventListener("mousemove", mouseMoved, false);
        console.log('mouseDown');
    },
    mouseUp: function(e) {
        e.target.removeEventListener("mousemove", mouseMoved, false);
        console.log('mouseUp');
    }
};
function mouseMoved(e) {
    console.log("mouseMoved");
}

While this one is not : 虽然这不是:

var imageMover = {
    mouseDown: function(e) {
        e.target.addEventListener("mousemove", this.mouseMoved, false);
        console.log('mouseDown');
    },
    mouseUp: function(e) {
        e.target.removeEventListener("mousemove", this.mouseMoved, false);
        console.log('mouseUp');
    },
    mouseMoved: function(e) {
        console.log("mouseMoved");
    }
};

To give a little more context: There are thumbnails you can click on. 提供更多背景信息:您可以单击一些缩略图。 When you click on it, the image is added to a container, and the events mouseUp and mouseDown are added to the image. 当您单击它时,会将图像添加到容器,并将事件mouseUp和mouseDown添加到图像。 When someone click on the image, i'd like the event mouseMouve to be attached so I can follow the image position. 当有人单击图像时,我希望附加事件mouseMouve,以便我可以跟踪图像的位置。

mouseUp and mouseDown are well attached, and well triggered, but mouseMouve only works when it is not inside my imageMover object. mouseUp和mouseDown连接良好且触发良好,但是mouseMouve仅在不在我的imageMover对象中时才起作用。 It seems to be a scope problem, but I can't figure why it acts like that. 这似乎是一个范围问题,但我不知道为什么会这样。

In advance, many thanks ! 预先,非常感谢!

The this from this.mouseMoved is refering to the event target, which is the DOM element not the object storing the methods. this.mouseMoved中的this引用事件目标,它是DOM元素,而不是存储方法的对象。

 var imageMover = { mouseDown: function(e) { console.log( 'this is refering to => ', this ); e.target.addEventListener("mousemove", this.mouseMoved, false); } }; document.querySelector( '.container' ).addEventListener( 'mousedown', imageMover.mouseDown ); 
 .container { width: 500px; height: 100px; border: 1px solid #000; } 
 <div class="container"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM