![](/img/trans.png)
[英]How to differentiate between a click and a drag using jQuery, but get only one click event
[英]How to differentiate between click and drag/drop event?
我有一個問題,元素既可拖動也有點擊事件。
$('.drag').mousedown(function() {
//...
});
$('.class').click(function() {
//...
)};
<div class="drag class"></div>
當我拖放元素時,click事件也會被觸發。 怎么預防?
您也可以使用mousemove和mousedown事件一起執行某些操作來禁用click事件:
var dragging = 0;
$('.drag').mousedown(function() {
$(document).mousemove(function(){
dragging = 1;
});
});
$(document).mouseup(function(){
dragging = 0;
$(document).unbind('mousemove');
});
$('.class').click(function() {
if (dragging == 0){
// default behaviour goes here
}
else return false;
)};
你應該能夠通過停止mousedown事件的傳播來做到這一點。
$('.drag').mousedown(function(event){
event.stopPropagation();
});
您可能必須確保在單擊事件之前附加了此事件。
在我的情況下,選擇的答案沒有奏效。 所以這是我的解決方案正常工作(可能對某人有用):
var dragging = 0;
$(document).mousedown(function() {
dragging = 0;
$(document).mousemove(function(){
dragging = 1;
});
});
$('.class').click(function(e) {
e.preventDefault();
if (dragging == 0){
alert('it was click');
}
else{
alert('it was a drag');
}
});
我注意到如果在單擊事件之前注冊了拖動事件,則不會發生所描述的問題。 這是一個示例代碼:
此代碼創建了上述問題:
var that = this;
var btnId = "button_" + this.getId();
var minView = $("<div>", {"id":btnId, style:"position:absolute; top:"
+ this.options.style.top + ";left:" + this.options.style.left + ";border:1px solid gray;padding:2px"});
minView.html(this.getMinimizedTitle());
minView.click(function expendWidget(event) {
$("#" + btnId).remove();
that.element.css({"left":that.options.style.left, "right":that.options.style.right});
that.element.show();
});
minView.draggable();
minView.on("drag", this.handleDrag.bind(this));
this.element.parent().append(minView);
此代碼不會產生問題:
var that = this;
var btnId = "button_" + this.getId();
var minView = $("<div>", {"id":btnId, style:"position:absolute; top:"
+ this.options.style.top + ";left:" + this.options.style.left + ";border:1px solid gray;padding:2px"});
minView.html(this.getMinimizedTitle());
minView.draggable();
minView.on("drag", this.handleDrag.bind(this));
minView.click(function expendWidget(event) {
$("#" + btnId).remove();
that.element.css({"left":that.options.style.left, "right":that.options.style.right});
that.element.show();
});
this.element.parent().append(minView);
沒關系,但是你應該記住,用戶可以在點擊過程中輕微移動鼠標而不會注意到。 所以他認為嗨點擊了你 - 他拖着他
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.