【发布时间】:2019-05-17 12:46:44
【问题描述】:
我正在使用 vanilla Javascript 制作拖放应用程序。
因此,只有 1 个可拖动元素,它工作得很好,但是当我有多个时,它们实际上并没有拖动,只有其中一个可以拖动。
我需要区分这些元素以了解我当前正在移动哪一个,但我想不出任何解决方案。
我做了一些研究并尝试使用“ondrag”属性,但我无法从中做出一些事情。
到目前为止,这是我的代码:
const filled = document.querySelectorAll('.fill');
const empties = document.querySelectorAll('.empty');
//fill listeners
for (const fill of filled){
fill.addEventListener('dragstart', dragStart);
fill.addEventListener('dragend', dragEnd);
}
for(const empty of empties)
{
empty.addEventListener('dragover', dragOver);
empty.addEventListener('dragenter', dragEnter);
empty.addEventListener('dragleave', dragLeave);
empty.addEventListener('drop', dragDrop);
}
var element_id = "";
//drag functions
function dragStart(){
this.className += ' hold';
setTimeout(() => this.className = 'invisible', 0);
}
function dragEnd(){
this.className = 'fill';
}
function dragOver(e){
e.preventDefault();
}
function dragEnter(e){
e.preventDefault();
this.className += ' hovered';
}
function dragLeave(){
this.className = 'empty';
}
function dragDrop(){
document.GetElementById(id).className = 'empty';
this.append(element_id)
}
function _(id){
element_id = id;
}
body {
background: darkcyan;
}
.fill {
background-image: url('https://source.unsplash.com/random/50x50');
position: relative;
height: 50px;
width: 50px;
top: 2px;
left: 2px;
cursor: pointer;
}
.holders{
display: inline-block;
height: 55px;
width: 55px;
margin: 10px;
border: 3px gold solid;
background: pink;
position: relative;
}
.empty{
display: inline-block;
height: 55px;
width: 55px;
margin: 5;
border: 3px black solid;
background: grey;
position: relative;
top: 80px;
left: 50px;
}
.hold{
border: solid lightgrey 4px;
}
.hovered{
background: white;
border-style: dashed;
}
.invisible{
display: none;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>DragnDrop</title>
</head>
<body>
<div class="holders">
<div id="0" ondrag="_(id)" class="fill" draggable="true"></div>
</div>
<div class="holders">
<div id="1" class="fill" draggable="true"></div>
</div>
<div class="holders">
<div id="2" class="fill" draggable="true"></div>
</div>
<div class="holders">
<div id="3" class="fill" draggable="true"></div>
</div>
<br>
<div value="0" class="empty"></div>
<div value="0" class="empty"></div>
<script src="js/main.js"></script>
</body>
</html>
我对 javascript 不是很有经验,所以我会很感激任何解释。 谢谢。
【问题讨论】:
标签: javascript html css drag-and-drop