JQuery Draggable - 恢复到原始位置不起作用

时间:2015-02-25 02:57:07

标签: jquery jquery-ui jquery-ui-draggable

设置为还原的可拖动元素将恢复到原始位置PLUS左侧的多个像素。我只是希望元素恢复到原来的位置。

var browser;    

if(navigator.userAgent.indexOf("Chrome") != -1 ){
   browser = 'webkit';
} else if(navigator.userAgent.indexOf("Opera") != -1 ){
   browser = 'webkit';
} else if(navigator.userAgent.indexOf("Firefox") != -1 ){
   browser = 'firefox';
} else if(navigator.userAgent.indexOf("Safari") != -1 ){
   browser = 'webkit';
} else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )){
   browser = 'ie'; 
} 

if(browser == 'ie'){
    $('.draggable').css('cursor', 'move');
}

$('.draggable').each(function(i,el){
    var tLeft = Math.floor(Math.random()*350),
        tTop  = Math.floor(Math.random()*450);
    var rotate=Math.floor(Math.random() * (360 - 1 + 1)) + 1;
    $(el).css({ 
         '-ms-transform': 'rotate(' + rotate + 'deg)',
         '-webkit-transform': 'rotate(' + rotate + 'deg)',
         'transform': 'rotate(' + rotate + 'deg)',
        })    
    $(el).css({position:'absolute', left: tLeft, top: tTop});
});


$("[id^=draggable_]").draggable({
  stack: '#draggables_container div',
  revert: true
});

$(".drag_slot").droppable({   
  hoverClass: "hover",
  accept: '#draggables_container div',
  drop: dropped
});

function dropped(event, ui) {
var slotNumber = $(this).data('slot');
var draggableNumber = ui.draggable.data('draggable');
if (slotNumber == draggableNumber) {
r = 0;
if(browser == 'webkit'){
ui.draggable.css('-webkit-transform','rotate(' + (r += 360) + 'deg)');  
} else {
ui.draggable.css('transform','rotate(' + (r += 360) + 'deg)');
}
if($(this).is(':empty')){
ui.draggable.position({
    my:        "left top",
    at:        "left+5 top",
    of:        this, 
    collision: "fit"
})
} else {
    ui.draggable.position({
    my:        "left top",
    at:        "left+35 top",
    of:        this, 
    collision: "fit"
})
}
ui.draggable.draggable('disable');
ui.draggable.draggable( 'option', 'revert', false );
ui.draggable.draggable.toggleClass('drag_disable');
}
}

请参阅http://jsfiddle.net/gh3bk7xo/6/

如果你反复拖动元素,你会发现它们每次都会更靠近容器的左边缘......如果拖得足够多,它们实际上可以移出屏幕。

1 个答案:

答案 0 :(得分:1)

draggable的位置生成函数似乎没有rotate s。但是,由于您无论如何手动生成原始位置,您只需将它们存储在单独的变量中并自行恢复拖动:

var positions = {}
$('.draggable').each(function(i,el){
    // ... snip
    positions[$(this).attr("id")] = {position:'absolute', left: tLeft, top: tTop};
    $(el).css(positions[$(this).attr("id")]);
});

$(".draggable").draggable({ // why the different selectors?
  // ... snip
  revert: false,
  stop: function() {
      if ( !$(this).draggable("option", "disabled") ) { // since disabled in droppable
          $(this).animate(positions[$(this).attr("id")], 500);
      }
  }
});

以下是样本小提琴:http://jsfiddle.net/w48evbd1/