如果鼠标在“mousedown”事件之后移动,我试图阻止触发点击事件。目前我正在通过条件和 bool 值手动完成所有操作。我仍然没有让它按照我想要的方式工作,我觉得这只是实现这一目标的一种糟糕方法。
var mousemove = false;
var mousedown = false;
var cancelClick = false;
$('.example').click( function() {
if (!cancelClick) {
if ( $(this).attr('id') === 'example-green') {
$(this).attr('id', 'example-blue');
} else {
$(this).attr('id', 'example-green');
}
}
cancelClick = false;
});
$('.example').mousedown( function() {
mousedown = true;
});
$('.example').mouseup( function() {
if (mousemove) {
cancelClick = true;
}
mousedown = false;
mousemove = false;
});
$('.example').mousemove( function() {
if (mousedown) {
mousemove = true;
}
});
有没有更简单的方法来实现这个?最好是阻止处理点击事件或将它们从待处理事件队列中删除的方法(我不确定它们是否在您释放鼠标之前排队)。这样回调本身就不会与 this 的实现耦合。
最佳答案
我只是将鼠标的 x/y 坐标存储在 mousedown 上,并将其与单击时的当前坐标进行比较。
$('.example')
.on('mousedown', function() {
$(this).data("initcoords", { x: event.clientX, y: event.clientY });
})
.on('click', function() {
var initCoords = $(this).data("initcoords") || { x: 0, y: 0 };
if (event.clientX === initCoords.x && event.clientY === initCoords.y) {
if ( $(this).attr('id') === 'example-green') {
$(this).attr('id', 'example-blue');
} else {
$(this).attr('id', 'example-green');
}
$(this).data('initcoords', {x:-1, y:-1});
}
});
您还可以打开和关闭点击事件。它更简洁一些,但我想知道与上述方法相比设置事件处理程序的开销。
$('.example')
.on('mousedown', function() { $(this).one("click", handleClick); })
.on('mousemove mouseout', function() { $(this).off('click'); });
function handleClick(){
var $el = $('.example');
if ( $el.attr('id') === 'example-green') {
$el.attr('id', 'example-blue');
} else {
$el.attr('id', 'example-green');
}
}
关于javascript - 如果在 mousedown 之后移动鼠标,则取消传入的 jQuery 单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23944545/