[英]jQuery - How to destroy an event which is attached to an element?
我有一些代碼行,它們會在mousedown
-ed之后將元素移動到鼠標位置。
我想刪除它相連的事件,這樣就不會再跟隨鼠標的位置之后是mouseup
-ed!
元素依然沿用了鼠標后, mouseup
!
我希望它在mousedown
上跟隨鼠標,並在mouseup
后停止跟隨鼠標! 如何從元素中刪除mousemove
偵聽器?
這是JS
jQuery(document).ready(function ($) {
$(".crossY").on("mousedown", function (e) {
var j = $(this);
$(document).on("mousemove", function (e) {
j.css({
"top": e.pageY,
"left": e.pageX
});
});
})
$(".crossY").on("mouseup", function (e) {
var j = $(this);
$(document).on("mousemove", function (e) {
j.css({
"top": j.css("top"),
"left": j.css("left")
});
});
});
});
要刪除鼠標偵聽器,您需要使用jQuery .off
方法。 為了使其易於使用,您應該命名mousemove
事件。 這將允許您輕松分離必要的mousemove
偵聽器。
在mousedown
里面我們想要附加聽眾
$(document).on('mousemove.following', function (e) { /* my event handler */ })
在mouseup
內部,我們想要分離監聽器
$(document).off('mousemove.following')
following
命名空間確保不會分離其他事件偵聽器。
這是一個工作的例子 (你的jsfiddle除了更新)。
您可能想要做的另一件事是將移動部件置於鼠標下方的中心位置。
$(".crossY").on("mousedown", function (e) {
var j = $(this);
var height = j.height(), width = j.width();
$(document).on("mousemove", function (e) {
j.css({
"top": e.pageY - height/2,
"left": e.pageX - width/2,
});
});
})
減去元素高度和寬度的一半使元素保持在鼠標下方的中心,這也將確保甚至觸發mouseup
。
嘗試使用bind()
和unbind()
如下所示: DEMO
jQuery(document).ready(function ($) {
$(".crossY").on("mousedown", function (e) {
var j = $(this);
$(document).bind("mousemove", function (e) {
j.css({
"top": e.pageY-10,
"left": e.pageX-10
});
});
})
$(".crossY").on("mouseup", function (e) {
var j = $(this);
$(document).unbind("mousemove");
});
});
嘗試
jQuery(document).ready(function ($) {
$(".crossY").on("mousedown", function (e) {
var j = $(this);
$(document).on("mousemove", function (e) {
j.css({
"top": e.pageY,
"left": e.pageX
});
});
})
$(".crossY").on("mouseup", function (e) {
var j = $(this);
$(document).off("mousemove");
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.