【发布时间】:2016-03-23 09:56:13
【问题描述】:
我有一个页面,其中包含可以放入各种容器中的项目。我必须在任何给定时间将可拖动项目添加到它当前结束的容器中,以便根据 css 以某种方式对其进行样式设置,这取决于可拖动项目和放置目标类的组合。不能在 javascript 中应用这种样式 - 样式必须来自 CSS。
问题来了,因为我在可拖动的容器之前添加了position: relative 属性。当我移动它时,这会弄乱可拖动助手相对于我的鼠标的位置。
这是一个非常简化的问题演示:
$('.draggable').draggable({
drag: _onDrag,
helper: function () {
return $(this).clone().prependTo('#div1');
}
});
function _onDrag(event, ui) {
ui.helper.hide();
var elementAtPoint = $(document.elementFromPoint(event.clientX, event.clientY));
if(elementAtPoint.hasClass('dropTarget')) {
ui.helper.prependTo(elementAtPoint);
}
ui.helper.show();
}
.draggable {
display: inline-block;
background: red;
height:50px;
width: 50px;
}
#div1 .item1 {
background: green;
}
#div1 .item2 {
background: purple;
}
#div2 .item1 {
background: blue;
}
#div2 .item2 {
background: orange;
}
#div1, #div2 {
position: relative;
width: 100px;
height: 100px;
border: 1px solid #000;
display: inline-block;
}
<script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<div class="draggable item1">
Drag me!
</div>
<div class="draggable item2">
Drag me too!
</div>
<div id="div1" class="dropTarget">
Drag the box here first...
</div>
<div id="div2" class="dropTarget">
Then drag it here :(
</div>
在不更改 css 或 html 的情况下,我可以做些什么来防止可拖动对象丢失其位置?
【问题讨论】:
标签: html css jquery-ui draggable