Scroll div when element is dragging without moving

2019-03-31 06:34发布

问题:

I developped a code including a table with all its cells as droppable. The table container is div with a fix height and a scrollbar.

I would like drag an element (yellow square in my example) into the last table cell at the bottom of my table. Everything works fine, but to activate the scrollbar of my div container when I am dragging the element, I must move the mouse all the time.

Is there a possibility to scroll down automatically when my element is dragging near the bottom of my div container without moving mouse?

Here is my example : http://jsbin.com/upunek/19/edit

Thanks in advance

回答1:

I figure it out this morning.

I created setInterval function when the drag event position is located at 70px of the border

Here is the fiddle I made : http://jsfiddle.net/pPn3v/22/

var yellow = $('#yellow');
var offset = yellow.offset();
var offsetWidth = offset.left + yellow.width();
var offsetHeight = offset.top + yellow.height();

var red = $('#red');

var intRightHandler = null;
var intLeftHandler = null;
var intTopHandler= null;
var intBottomHandler= null;
var distance = 70;
var timer = 100;
var step = 10;


function clearInetervals()
{
    clearInterval(intRightHandler);
    clearInterval(intLeftHandler);
    clearInterval(intTopHandler);
    clearInterval(intBottomHandler);    
}

red.draggable({
    start : function(){},
    stop: function(){clearInetervals(); },    
    drag : function(e){
        var isMoving = false;        
        //Left
        if((e.pageX - offset.left) <= distance)
        {
            isMoving = true;
            clearInetervals();            
            intLeftHandler= setInterval(function(){
                yellow.scrollLeft(yellow.scrollLeft() - step)
            },timer);
            console.log('left')
        }

        //Right
        if(e.pageX >= (offsetWidth - distance))
        {
            isMoving = true;
            clearInetervals();            
            intRightHandler = setInterval(function(){
                yellow.scrollLeft(yellow.scrollLeft() + step)
            },timer);
            console.log('right')
        }

        //Top
        if((e.pageY - offset.top) <= distance)
        {
            isMoving = true;
            clearInetervals();            
            intTopHandler= setInterval(function(){
                yellow.scrollTop(yellow.scrollTop() - step)
            },timer);
            console.log('top')
        }                          

        //Bottom
        if(e.pageY >= (offsetHeight - distance))
        {
            isMoving = true;
            clearInetervals();            
            intBottomHandler= setInterval(function(){
                yellow.scrollTop(yellow.scrollTop() + step)
            },timer);
            console.log('bottom')
        }     

        //No events
        if(!isMoving)
           clearInetervals();  
    }
});