3

我的身体里散布着一些 div:

<div id="one"></div>
<div id="two"></div>
<div id="three"></div>

这些都可以用 jqueryUI 拖动:

var $divs = $('#one, #two, #three');
$divs.draggable({ start: dragStart,
                  cursor: 'move',     
                  stop: dragStop,
                  drag: whileDrag });

如果当前拖动的元素被拖动到其中一个 div 上,我想触发一个事件。但不像 jqueryUI 那样droppable你必须停止拖动才能触发。它应该在拖动时开火!除了实时读取偏移量之外,还有其他方法吗?

任何帮助深表感谢!谢谢

4

1 回答 1

3

测试jsFiddle

// function to determine, that rectangles intersect
var intersect = function(a,b){
    return(
            (
              (
                ( a.x >= b.x && a.x <= b.x1 ) || ( a.x1 >= b.x && a.x1 <= b.x1  )
              ) && (
                ( a.y >= b.y && a.y <= b.y1 ) || ( a.y1 >= b.y && a.y1 <= b.y1 )
              )
            ) || (
                   (
                     ( b.x >= a.x && b.x <= a.x1 ) || ( b.x1 >= a.x && b.x1 <= a.x1  )
                   ) && (
                     ( b.y >= a.y && b.y <= a.y1 ) || ( b.y1 >= a.y && b.y1 <= a.y1 )
                   )
                 )
            ) || (
                  (
                    (
                      ( a.x >= b.x && a.x <= b.x1 ) || ( a.x1 >= b.x && a.x1 <= b.x1  )
                    ) && (
                      ( b.y >= a.y && b.y <= a.y1 ) || ( b.y1 >= a.y && b.y1 <= a.y1 )
                    )
            ) || (
                  (
                   ( b.x >= a.x && b.x <= a.x1 ) || ( b.x1 >= a.x && b.x1 <= a.x1  )
                  ) && (
                   ( a.y >= b.y && a.y <= b.y1 ) || ( a.y1 >= b.y && a.y1 <= b.y1 )
                  )
               )
            );
}

// elements - elements to fire dragover event on draggable element hover 
var coordinates = {},
    elements = ['#two', '#three'];
    $('#one').draggable({
        start: dragStart,
        cursor: 'move',
        stop: dragStop,
        create: function(event, ui){
            for (var k in elements){
                coordinates[k] = {
                    x: $(elements[k]).offset().left,
                    y: $(elements[k]).offset().top,
                    x1: $(elements[k]).offset().left + $(elements[k])[0].clientWidth,
                    y1: $(elements[k]).offset().top + $(elements[k])[0].clientHeight
                }
            }
        },
        drag: function(event, ui){
            var draggableElementCoord = {
                x: ui.offset.left,
                y: ui.offset.top,
                x1: ui.offset.left + ui.helper[0].clientWidth,
                y1: ui.offset.top + ui.helper[0].clientHeight
            };
            for (var k in elements){
                if (intersect(coordinates[k], draggableElementCoord)){
                    $(elements[k]).trigger('dragover');
                }
            }
        }
    });

使用:

$(document).on('dragover', '#two', function(e){
  // your code
});
于 2013-05-31T16:22:06.933 回答