2

我的 jQuery 代码中有一个可拖动的元素,并且同一个元素有一个点击功能。一切正常,但是当我拖动元素时,它也会运行单击功能。我能做些什么来防止这种情况发生?

这是我的 HTML:

<div class="container">
  <div class="clickable"></div>
  <div id="content">A!</div>
</div>

具有“容器”类的 div 是可拖动的,并且.clickable具有click切换具有 id 的 div 的功能content

4

1 回答 1

2

As suggested in my comment you can add a class to the element (eg dragging) when you start dragging in the start function of the draggable, than check in the click handler if the element (or the parent of it in your case) have to class or alternatively fire the function.

Code:

$(document).ready(function () {

    $('.container').draggable({
        start: function (event, ui) {
            $(this).addClass('dragging');
        }
    });

    $('.clickable').click(function (event) {
        if ($(this).parent().hasClass('dragging')) {
            $(this).parent().removeClass('dragging');
        } else {
            //alert("real click");
            $("#content").toggle();
        }
    });
});

Maybe there are alternatives to this, but is the only solution that I used.

Demo: http://jsfiddle.net/IrvinDominin/N3bKb/

Docs:

于 2013-08-18T16:08:41.800 回答