2014-11-02 105 views
0

我有一個容器中的可排序元素居中(margin:0 auto)。問題是,當我開始排序時,所選元素跳轉到左側,因爲它們完全變成了位置。JQUERY UI可排序居中元素

這裏是一個說明該問題的小提琴: http://jsfiddle.net/annam/35MC3/28/

我試圖讓偏移位置排序開始前(用鼠標按下監聽器),然後將這個位置的元素時排序開始:

function onMouseDown() 
{ 
    startPosition = $(this).offset(); 
} 

function startSort(event,ui) 
{ 
    $(ui.item).css(startPosition); 
} 

沒有工作。然後,我試着明確地將ui.sortable.originalposition設置爲特定的頂部和左側位置,但這也不起作用。

有什麼建議嗎?

請注意,我無法更改HTML的結構並引入新的容器。

回答

0

試試這個:http://jsfiddle.net/lotusgodkk/35MC3/113/

$('#container').sortable({ 
    axis: 'y' 
}); 
$('.draggable:not(.ui-sortable-helper)').mouseover(function() { 
    var p = $(this).offset(); 
    $(this).css({ 
     top: p.top + 'px', 
     left: p.left + 'px' 
    }) 
}); 

說明ui-sortable-helper是分配給排序項類。所以在這裏,我們只是設置項目的初始top,left值,只有當它被徘徊但沒有排序。之所以沒有爲你工作是因爲ui.offsetstart功能undefined

0

可以使用helper選項返回使用position() jQuery UI的實用方法定位自定義元素如下:

$('#container').sortable({ 
 
    helper: function(event, elm) { 
 
    return $(elm).clone().position({ 
 
     my: "left", 
 
     at: "left", 
 
     of: elm 
 
    }); 
 
    }, 
 
    axis: 'y' 
 
})
* { 
 
    margin: 0; /*for stack snippet demo*/ 
 
    padding: 0; 
 
} 
 
#container { 
 
    position: relative; 
 
    width: 200px; 
 
    height: 300px; 
 
    text-align: center; 
 
    border: 1px solid green; 
 
} 
 
.draggable { 
 
    width: 100px; 
 
    height: 100px; 
 
    background: yellow; 
 
    margin: 10px auto; 
 
    cursor: move; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> 
 
<div id="container"> 
 
    <div class="draggable"></div> 
 
    <div class="draggable"></div> 
 
</div>