滚动可拖动项目的内容时禁用jQuery拖动 [英] Disabling jQuery drag when scrolling contents of draggable item

查看:57
本文介绍了滚动可拖动项目的内容时禁用jQuery拖动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常不会做出这样的问题/答案,但是我想这样做,因为我已经问过这个问题超过20次,实际上没有一个答案有效.简而言之,问题在于,如果在可拖动的jQuery项内的任何地方都具有可滚动的内容(overflow: auto;,则当您单击并拖动滚动条时,父可拖动的容器会随之拖动.因此,我花了一些时间来制定解决方案

I don't normally make this sort of question / answer, but figured I'd do so, since I've seen this question asked 20+ times, and not a single answer actually works. In short, the problem is that if you have scrollable content (overflow: auto; anywhere inside of a draggable jQuery item, when you click and drag the scrollbar's the parent draggable container drags along with it. So, I spent some time working up a solution.

这是一些会出现此问题的html的示例:

Here's an example of some html that would present this problem:

<div class="draggable" style="width:100px;height:100px;">
  <div id="content" style="width:80px;height:80px;overflow:auto;">
    Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam id dolor id nibh ultricies vehicula ut id elit.
  </div>
</div>

将元素初始化为可拖动元素的典型方式如下:

The typical way you initialize an element to be draggable, is something like this:

$(".draggable").draggable()

推荐答案

解决方案是将初始化事件绑定到元素上的滚动事件以及其中任何子元素.然后,当任何一个子级调用滚动命令时,找到该元素的所有可拖动父级,然后在该元素上设置一个滚动数据元素.

The solution is to bind to the scroll event on the elements your initializing, and any of that elements children. Then, when any of the children invoke a scroll command, find all of the draggable parents of that element, and set a scrolled data element on that element.

在jQuery UI的当前版本(1.8.16)下,当您将鼠标悬停在滚动条上时,start事件始终会启动,并触发树,因此该解决方案在我的测试中效果很好.

Under jQuery UI's current version (1.8.16), the start event always kicks off when you mouseup on the scrollbar, and progates up the tree, so this solution works pretty well in my testing.

$(".draggable").draggable({
    start: function() {
        // if we're scrolling, don't start and cancel drag
        if ($(this).data("scrolled")) {
            $(this).data("scrolled", false).trigger("mouseup");
            return false;
        }
    }
}).find("*").andSelf().scroll(function() {               
    // bind to the scroll event on current elements, and all children.
    //  we have to bind to all of them, because scroll doesn't propagate.

    //set a scrolled data variable for any parents that are draggable, so they don't drag on scroll.
    $(this).parents(".ui-draggable").data("scrolled", true);

});

为方便您查看/尝试,我还包括了该问题的 jsfiddle .

For your viewing / dabbling pleasures, I've included a jsfiddle of the issue as well.

这篇关于滚动可拖动项目的内容时禁用jQuery拖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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