Jquery draggables: Removing an element changes position of other dropped elements

落爺英雄遲暮 提交于 2019-12-11 06:57:29

问题


When elements are placed / dropped (by dragging from one DIV to another) and then removing one in the dropped DIV, some of them are changing the position.

Here is a test scenario: http://jsfiddle.net/TcYHW/8/

And the main code:

<div id="dropwin"></div>
<div id="dragables">
    <div id="d1" class="d"></div>
    <div id="d2" class="d"></div>
    <div id="d3" class="d"></div>
    <div id="d4" class="d"></div>
</div>


$(".d").draggable({
        containment: '#dropwin',
        stack: '#dragables div',
        cursor: 'move',
      });

How can I avoid this?

I found, that the elements are placed in relative position to the starting position. How can I make them stick at the dropped position even if some are removed?

I found two near similar questions, but without an satisfying answer:

Remove in Jquery divs with draggables and resizables

jQuery draggable removing without changing position of other elements


回答1:


You need your elements to be positioned absolute. Then the deleted boxes won't affect the flow of the other elements.

You could just use css to position them absolute:

.d { 
    width: 50px;
    height: 50px;
    margin: 10px;
    display: inline-block;
    position: absolute;
}

But then you would have to manually place each box. The trick is to leave them positioned static (or relative after .draggable() gets done) and then use javascript to set their positions and set them to absolute positioning:

$('.d').each(function() {
    var top = $(this).position().top + 'px';
    var left = $(this).position().left + 'px';
    $(this).css({top: top, left: left});
}).css({position: 'absolute'});

Demo: http://jsfiddle.net/jtbowden/5S92K/




回答2:


I just made some edits in your jsFiddle demo and it seemed to be working

My Edits:

<div id="dropwin"></div>
<div id="dragables">
<div class="outer"><div id="d1" class="d"></div></div>
<div class="outer"><div id="d2" class="d"></div></div>
<div class="outer"><div id="d3" class="d"></div></div>
<div class="outer"><div id="d4" class="d"></div></div>
</div>
<button id="b1">Remove d1</button>
<button id="b2">Remove d2</button>
<button id="b3">Remove d3</button>
<button id="b4">Remove d4</button>

And in css:

#dropwin { width: 300px; height: 300px; border: 1px solid #f00;}
#dragables { width: 300px; height: 70px; border: 1px solid #00f; }
.d { width: 50px; height: 50px; margin: 10px; display: inline-block; }
#d1 { background: #f00; position:absolute; }
#d2 { background: #ff0; position:absolute; }
#d3 { background: #f0f; position:absolute; }
#d4 { background: #0ff; position:absolute; }
.outer{ margin:1px 2px 0 0; float:left; width:60px;}


来源:https://stackoverflow.com/questions/9643075/jquery-draggables-removing-an-element-changes-position-of-other-dropped-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!