[英]Issue in drag and drop functionality in JavaScript
I have a JavaScript drag and drop code,我有一个 JavaScript 拖放代码,
I have two classes div1
for drop and div2
for drag.我有两个类用于放置的div1
和用于拖动的div2
。
I have set position
of these two classes in CSS according to viewport
width
and height
and is mandatory here.我已经根据viewport
width
和height
在 CSS 中设置了这两个类的position
,这里是强制性的。
The problem is, when I drag and drop div2
to div1
, the element is not going and get placed inside div1
.问题是,当我将div2
拖放到div1
,元素不会移动并被放置在div1
。
How to make the class div2
dragged and get placed inside class div1
?如何使类div2
被拖动并放置在类div1
?
function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); console.log(data); assignedTabName = document.getElementById(data).className; console.log(assignedTabName); ev.target.appendChild(document.getElementById(data)); }
.div1 { border: 2px solid black; position: absolute; width: 23vw; height: 10vh; left: 10vw; bottom: 80vh; } .div2 { border: 2px solid black; position: fixed; width: 14vw; height: 12vh; left: 0vw; bottom: 60vh; background-color: #FFFF00; }
<div class="div1" id="drop1" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <br> <div class="div2" id="drag1" draggable="true" ondragstart="drag(event)"> <p width="336" height="69">hello</p> </div>
I believe your positioning rules of the divs is the problem.我相信你的 div 定位规则是问题所在。 If you remove the position: absolute
from the CSS of .div1
, and the position: relative
from the CSS of .div2
, then the drag-and-drop seems to work as expected.如果您删除position: absolute
距离的CSS .div1
和position: relative
从的CSS .div2
,然后按预期拖和下降似乎工作。
function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); console.log(data); assignedTabName = document.getElementById(data).className; console.log(assignedTabName); ev.target.appendChild(document.getElementById(data)); }
.div1 { border: 2px solid black; width: 23vw; height: 10vh; left: 10vw; bottom: 80vh; } .div2 { border: 2px solid black; width: 14vw; height: 12vh; left: 0vw; bottom: 60vh; background-color: #FFFF00; }
<div class="div1" id="drop1" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <br> <div class="div2" id="drag1" draggable="true" ondragstart="drag(event)"> <p width="336" height="69">hello</p> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.