jQuery拖放,在滚动的区域上放置元素时不会触发drop事件

时间:2013-04-28 17:44:39

标签: jquery-ui drag-and-drop

我正在使用jQuery UI进行拖放操作,一切都工作得非常好我唯一的问题是当我滚动然后我试图拖动一个元素并将其放在滚动区域中元素恢复到原来的位置。

只是为了澄清一下,默认情况下,当你将它拖出左边部分时它不会立即滚动,只有在你放下它之后,你才能选择该元素并向左或向下滚动它。

我在jsfiddle发布了一个示例,说明了我的问题。

$("#sidebar section span").draggable({
    cursor: "move",

    helper: "clone",

    revert: "invalid",

    //containment: "html",

    scroll: true
});

$("#main section").droppable({
    tolerance: 'fit',

    accept: "#sidebar section span",

    drop: function(e, ui)
    {
        console.log("Drop");

        var $draggedElement = ui.draggable;
        var $droppedArea = $(this);

        var droppedAreaLeft = $droppedArea.offset().left;
        var droppedAreaTop = $droppedArea.offset().top;

        $droppedArea.parent().css("overflow", "auto");

        var $draggableElement = $draggedElement.clone();

        $draggableElement.draggable({
            containment: [droppedAreaLeft, droppedAreaTop],

            scroll: true,

            scrollSpeed: 10,

            scrollSensitivity: 10
        });

        $droppedArea.append($draggableElement);

        $draggableElement.offset(ui.offset);
    },
});

1 个答案:

答案 0 :(得分:2)

我通过覆盖默认函数解决了这个问题,并为支持滚动的容差添加了一个新状态。

这是代码。

var _intersect = jQuery.ui.intersect;

jQuery.ui.intersect = function(draggable, droppable, toleranceMode) {

    if (!droppable.offset) {
        return false;
    }

    var x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width,
        y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height,
        l = droppable.offset.left, r = l + droppable.proportions.width,
        t = droppable.offset.top, b = t + droppable.proportions.height;

    switch (toleranceMode) {
        case "scroll":  
            var overflowBottom = droppable.element.scrollParent().scrollTop();
            var overflowRight = droppable.element.scrollParent().scrollLeft();;

            x1 = x1 - overflowRight;
            y1 = y1 - overflowBottom;
            x2 = x2 - overflowRight;
            y2 = y2 - overflowBottom;

            return (l <= x1 && x2 <= r && t <= y1 && y2 <= b);
        default:
            return _intersect.apply(this, arguments);
        }
};