问题描述
如果我不使用事件侦听器,则在此处拖动元素并将其放置在其他位置,效果很好,但是如果以这种格式使用它,则不会执行放置"操作.
Here i am drag an element and droping in another place it works well if i don't use event listeners but if i use it in this format it is not performing "place" operation.
此链接包含我的代码带有事件监听器"访问 http://jsfiddle.net/vishwateja2000/wHprQ/2/
this link contains my code "with Event Listeners"Visit http://jsfiddle.net/vishwateja2000/wHprQ/2/
此链接包含我的代码没有事件监听器"访问 http://jsfiddle.net/vishwateja2000/W2Pgq/1/
this link contains my code "without Event Listeners"Visit http://jsfiddle.net/vishwateja2000/W2Pgq/1/
document.getElementById("div2").addEventListener("mousedown", down);
function down(){
t=1;
document.getElementById("div1").addEventListener("mouseup", place);
document.getElementById("div1").addEventListener("mousemove",function() {
myFunction(event);
});
}
function place(){
document.getElementById("div1").removeEventListener("mousemove",function() {
myFunction(event);
});
}
function placeobj(x,y,x1,y1,l,r){
var cpx = parseInt(x);
var cpy = parseInt(y);
var amtx=parseInt(x1);
var amty=parseInt(y1);
var of=10;
document.getElementById("div2").style.left=cpx-amtx+l+"px";
document.getElementById("div2").style.top=cpy-amty+r+"px";
}
function myFunction(e) {
if(t==1){
x1 = e.clientX;
y1 = e.clientY;
var el=document.getElementById('div2');
l=el.offsetLeft;
r=el.offsetTop;
t=10;
}
x = e.clientX;
y = e.clientY;
placeobj(x,y,x1,y1,l,r);
}
推荐答案
问题是您在添加和删除 mousemove
事件时使用了不同的功能.尽管它们具有相同的功能,但是它们在内存中的功能不同,因此对待方式也有所不同.
The problem is that you used different functions when adding and removing the mousemove
event.Although they have the same functionality they are different functions in memory and so are treated differently.
看看固定版本: http://jsfiddle.net/PN3TA/
removeEventListener()
必须具有与 addEventListener()
中使用的事件名称相同的功能,才能删除正确的事件.该函数不能是匿名函数,因为它会创建一个新函数(尽管看起来可能相同).您需要使用一个引用(例如指针),该引用可以是命名函数或变量.
The removeEventListener()
has to have the same event name + function as used in the addEventListener()
to remove the right event. The function can't be an anonymous function as that creates a new function (although it might look the same). You need to use a reference (like a pointer) which can be a named function or a variable.
注意:另外,当将函数传递给这些方法时,如果原始函数希望获得与匿名函数相同的参数,则不必将其包装在匿名函数中.我的意思是,
NOTE: Also when passing a function to these methods you don't have to wrapped in an anonymous function if the original function expects to get the same arguments as the anonymous function. I mean, this:
document.getElementById("div1").addEventListener("mousemove",function() {
myFunction(event);
});
可以这样写,因为 myFunction()
需要一个 event
自变量,无论如何都会提供该自变量,从而为您节省了函数包装:
Could be written like this, because myFunction()
expects an event
argument which will be supplied anyway, saving you a function wrapper:
document.getElementById("div1").addEventListener("mousemove", myFunction);
这篇关于如何删除“鼠标"Java脚本中的事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!