使用 jQuery 拖放防止单击事件 [英] Preventing click event with jQuery drag and drop

查看:29
本文介绍了使用 jQuery 拖放防止单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面上有可使用 jQuery 拖动的元素.这些元素是否具有导航到另一个页面的点击事件(例如普通链接).

I have elements on the page which are draggable with jQuery. Do these elements have click event which navigates to another page (ordinary links for example).

防止点击在放置此类元素时触发同时允许点击它不是拖放状态的最佳方法是什么?

What is the best way to prevent click from firing on dropping such element while allowing clicking it is not dragged and drop state?

我对可排序元素有这个问题,但我认为有一个通用的拖放解决方案是很好的.

I have this problem with sortable elements but think it is good to have a solution for general drag and drop.

我已经为自己解决了这个问题.之后,我发现相同的解决方案 存在于 Scriptaculous,但是也许有人有更好的方法来实现这一目标.

I've solved the problem for myself. After that I found that same solution exists for Scriptaculous, but maybe someone has a better way to achieve that.

推荐答案

解决方案是添加单击处理程序,以防止单击在拖动开始时传播.然后在执行 drop 后删除该处理程序.为了防止点击起作用,最后一个操作应该延迟一点.

Solution is to add click handler that will prevent click to propagate on start of drag. And then remove that handler after drop is performed. The last action should be delayed a bit for click prevention to work.

可排序的解决方案:

...
.sortable({
...
        start: function(event, ui) {
            ui.item.bind("click.prevent",
                function(event) { event.preventDefault(); });
        },
        stop: function(event, ui) {
            setTimeout(function(){ui.item.unbind("click.prevent");}, 300);
        }
...
})

可拖动的解决方案:

...
.draggable({
...
        start: function(event, ui) {
            ui.helper.bind("click.prevent",
                function(event) { event.preventDefault(); });
        },
        stop: function(event, ui) {
            setTimeout(function(){ui.helper.unbind("click.prevent");}, 300);
        }
...
})

这篇关于使用 jQuery 拖放防止单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆