1

jQuery我可能对'sdraggable()与 css 的结合有一个非常具体的问题。divs我的身体里有很多都是可以拖动的:

for(var i = 0; i < 150; i++) {
        var randomleft = Math.floor(Math.random()*1000);
        var randomtop = Math.floor(Math.random()*1000);
        var appenditem = '<div id="cube'+i+'" style="position: absolute; border: 2px #000 solid; left: '+randomleft+'px; top: '+randomtop+'px; width: 15px; height: 15px;"></div>'
        $('body').append(appenditem);
        cubes.push($('#cube'+i));
    }

$('div').draggable();

到目前为止,一切都很好。

然后我有一个固定<div id="fixed">在我身体的特定位置,可以说:top: 50px; left: 50px;

我想做的是触发事件处理程序dragstop并获取当前拖动的dragstop div与固定div之间的距离。

例如,在 dragend 上,一个 div 被拖到:top: 500px; left: 40px然后我想要这些值:+450并且-10因为 div 是top: +450px-10pxfrom #fixed

我该怎么做,尤其是负值。

提前致谢

4

2 回答 2

2

现场演示

jQuery(function($) {

   var allCubes  = '',
       $fixed    = $('#fixed'),
       fixedOffs = $fixed.offset();

    for(var i = 0; i < 150; i++) {
        var randomleft = Math.floor(Math.random()*1000),
            randomtop  = Math.floor(Math.random()*1000);
        allCubes += '<div id="cube'+i+'" style="position: absolute; border: 2px #000 solid; left: '+randomleft+'px; top: '+randomtop+'px; width: 15px; height: 15px;"></div>';
    }  

    $('body').append(allCubes); // Outside loop! (60% more performance)

    $('[id^="cube"]').draggable({
        stop: function(ev, ui){
            var pos = ui.position; // or use ui.offset if you need document related position
            // var orgPos = ui.originalPosition; // if you need it
            alert(
               ( pos.left - fixedOffs.left )+' \n '+
               ( pos.top  - fixedOffs.top  )
            );
        }
    });  

});
于 2013-10-23T22:59:51.827 回答
0

当你使用 jQuery 时,你所需要的只是offset()你的固定元素。停止回调中的可拖动ui对象也提供了这些信息,剩下的就是简单的数学运算:

// assuming the stop callback of draggable()
stop: function( event, ui ) {
    var fixedOffset = $("#fixed").offset();

    return {
        top: ui.offset.top - fixedOffset.top,
        left: ui.offset.left - fixedOffset.left,
    }
}

使用您的示例的值,此函数将返回具有以下值的对象文字:{ top: 450, left: -10 }

于 2013-10-23T22:43:05.797 回答