简体   繁体   English

jQuery可拖动/可拖放功能

[英]jquery draggable/droppable as a function

I am trying to create a function so that i can have multiple drag/droppables in a page. 我正在尝试创建一个函数,以便在页面中可以有多个拖放对象。 For that i made the following: 为此,我做了以下工作:

function apDrag(dragId,container) {
    $(function() {
          $('#'+dragId).draggable({ 
                revert: "invalid", 
                drag: function(e) {
                    var currentPos = $('#'+dragId).position();
                    $('#data').html('Left: '+currentPos.left+ ' Top: '+currentPos.top);
                }
            });
          $('#'+container).droppable({
            tolerance: 'fit',
            greedy: true,
            drop: function( event, ui ) {

                    // For some reason "dragId" defaults to "dragger2" here
                    // console.log(dragId); = dragger2; even though first function passes "dragger1" as dragId

                    $('#'+dragId).draggable({revert:"invalid"});
                    pos = $('#'+dragId).position();
                    cPosLeft = pos.left;
                    cPosTop = pos.top;
                    $('#data').html('Left: '+cPosLeft + ' Top: '+ cPosTop);
                    $('#'+dragId).html('ID: <b>'+dragId+'</b>');
                }
            });
      });
}
apDrag('dragger','container');
apDrag('dragger2','container');

The problem here is that for some reason the "dragId" being passed into the drop function of the droppable, always become the same, and are not "dragger1", "dragger2" as it should be. 这里的问题是由于某种原因,传递给droppable的drop函数的“ dragId”总是相同,而不是应有的“ dragger1”,“ dragger2”。 It always reverts to "dragger2" for both of the divs. 对于两个div,它始终都还原为“ dragger2”。

PS: The reason I am creating a droppable for each function is that they eventually will have different settings for each draggable. PS:我为每个功能创建一个可放置对象的原因是,它们最终将对每个可拖动对象具有不同的设置。

Please see fiddle: here for a better explanation 请参阅小提琴: 这里有更好的解释

Thanks to A. Wolff, i found that using: 感谢A. Wolff,我发现使用:

ui.draggable

in the drop function, i could get the correct id of the dragged div: 在放置函数中,我可以获取拖动的div的正确ID:

$('#'+container).droppable({
 tolerance: 'fit',
 greedy: true,
 drop: function( event, ui ) {
 var correctID = $(ui.draggable).attr("id");
 // id of dragged element is now "correctID"
 }
});

A. Wolff also updated the fiddle here A. Wolff在这里也更新了小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM