jQuery UI, Draggable, Droppable, Auto Scroll

2019-03-20 03:51发布

问题:

I have a set of droppable li elements that accepts a draggable icon. The list of items is in a scrollable div element. I put together a simple example here: http://www.nerdydork.com/demos/dragscroll/

I'm wondering if there is a way to autoscroll the list of elements when you are dragging the draggable element. For example, let's say you are somewhere in the middle, like http://www.nerdydork.com/demos/dragscroll/#j . As you approach the top of the div, it will start scrolling up, as you approach the bottom of the div it will start scrolling down.

Anyone know how to accomplish this with jQuery?

UPDATE

I'm getting closer. I created fixed div on the upper & lower portions of the container div. When hovering over it starts an autoscroll using http://plugins.jquery.com/project/aautoscroll

Now the problem is when I hover over the lower area, it messes up my draggable on the letters. It only seems to be a problem with the lower autoscroll area though.

To see the bug I'm talking about, watch this short video: http://screencast.com/t/JBFWzhPzGfz

Notice how when it autoscrolls down, the hover is NOT over the right letter. Toward the end of the video you can see that if you hover over the left margin of the list, then it somehow resets and seems to work again.

回答1:

Setting the "refreshPositions: true" option for the draggable will cause jQuery to recalculate the offsets on every mouse event. That should fix your problem.



回答2:

you can also try to use an interval function: http://jsfiddle.net/msszhwzf/6/

for (var i = 0; i < 10; i++) {
    $("#sortableContainer").append('<div class="sortable"></div>');
    $("#droppableContainer").append('<div class="droppable"></div>');
};

var adding = 0
var scrollInterval = null;

$("#sortableContainer").sortable({
    refreshPositions: true,
    start: function (e, ui) {
        scrollInterval = setInterval(function () {
            var foo = $("#droppableContainer").scrollTop();
            $("#droppableContainer").scrollTop(foo + adding);
        }, 50)
    },
    stop: function (e, ui) {
        clearInterval(scrollInterval);
    },
    sort: function (e, ui) {
        var top = e.pageY - $("#droppableContainer").offset().top
        if (top < 10) {
            adding = -15
        } else if (top > $("#droppableContainer").height() - 10) {
            adding = 15
        } else {
            adding = 0
        }
    },
});
$(".droppable").droppable({
    hoverClass: "active",
    accept: ".sortable",
    drop: function (event, ui) {
        ui.draggable.remove();
    },
})