我一直在尝试使用JQuery实现拖放功能。我有3'可拖动' divs和3' droppable' div的。 div为id' draggable1'我应该接受id为“droppable1' div”的div。等等。但是,它仅适用于一对div(draggable1和droppable1)。它不适用于其他两个。
我认为它与css定位有某种关系。当我没有为各个div设置边距属性时,它可以正常工作。但是,如果我想将div放在别处,那么功能就不再适用了。
这是我创建的一个小提琴:https://jsfiddle.net/3ews8j8x/
HTML
<center><h3>Drag and Drop</h3></center>
<div class="wrap">
<div class="draggables" id="draggable1"></div><br>
<div class="draggables" id="draggable2"></div><br>
<div class="draggables" id="draggable3"></div><br>
</div>
<div id="droppable1"></div>
<div id="droppable2"></div>
<div id="droppable3"></div>
CSS
body{
margin: 0;
}
.wrap{
width: 400px;
height: 300px;
background: #e3e3e3;
position: relative;
margin-top: 80px;
}
.draggables{
width: 20px;
height: 20px;
margin: auto;
position: absolute;
margin-left: 30px;
}
#draggable1{
background: #003366;
position: relative;
}
#draggable2{
background: #ffff00;
position: relative;
margin-top: 90px;
}
#draggable3{
background: #ff0000;
margin-top: -150px;
margin-left: 220px;
}
#droppable1{
width: 50px;
height: 50px;
background: #0000FF;
margin-left: 600px;
margin-top: -200px;
}
#droppable2{
width: 50px;
height: 50px;
background: #008080;
margin-left: 700px;
margin-top: -50px;
}
#droppable3{
width: 50px;
height: 50px;
background: #00cc00;
margin-left: 800px;
margin-top: -50px;
}
链接中提供了Javascript代码。
我想知道当我尝试更改div的位置时它为什么不起作用。可以不做或我做错了吗?我已经坚持这个问题超过3天了。任何帮助将不胜感激。
提前谢谢你。
答案 0 :(得分:1)
因此存在一些基本错误。首先,.draggables
设置为position:relative;
这些必须为absolute
。您将这些.draggables
与margins
对齐,您应该使用top
&amp; left
:
.draggables{
width: 20px;
height: 20px;
position: absolute;
}
#draggable1{
background: #003366;
}
#draggable2{
background: #ffff00;
top: 90px;
}
#draggable3{
background: #ff0000;
top: 150px;
left: 220px;
}