问题描述:

I have sortable elements in a container that are centered (margin: 0 auto). The problem is that when I start the sort, the selected element jumps to the left as they become position absolutely.

Here's a fiddle that illustrates the problem:

http://jsfiddle.net/annam/35MC3/28/

I tried getting the offset position before the sort starts (using a mousedown listener) and then applying this position to the element when sort starts:

function onMouseDown()

{

startPosition = $(this).offset();

}

function startSort(event,ui)

{

$(ui.item).css(startPosition);

}

Didn't work. I then tried explicitly setting ui.sortable.originalposition to a specific top and left position and this didn't work either.

Any suggestions?

Note that I cannot change the structure of the HTML and introduce new containers.

网友答案:

Try this : 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'
    })
});

Explanation: ui-sortable-helper is the class assigned to the sortable item. So here we just set the initial top,left values for the item only when it's hovered but not sorted. The reason why it didn't worked for you is because the ui.offset was undefined in start function.

网友答案:

You can use the helper option to return a custom element positioned using position() jQuery UI utility method as follows:

$('#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>
相关阅读:
Top