繁体   English   中英

如何区分点击和拖放事件?

[英]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.

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