我正在尝试解决此拖放代码的问题。当我尝试拖动一个不是8的图像时,8会自动上升,而我无法将其他任何图像拖动到div框中。
在拖动图像后,如果进入google中的检查模式,如果您尝试将8拖动到图像应进入的框中,则google会显示一条消息:
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at drop (Assignment10.html:41)
at HTMLDivElement.ondrop (Assignment10.html:50)
如何解决此代码?
我实际上没有尝试过任何东西,因为我不知道如何解决此代码。
//JS for the drag-and-drop
function drag(event) {
event.dataTransfer.setData("Text", event.target.id);
}
function permitDrop(event) {
event.preventDefault();
}
function drop(event) {
event.preventDefault();
var data = event.dataTransfer.getData("Text");
event.target.appendChild(document.getElementById(data));
}
#draginto {
width: 1520px;
height: 200px;
border-style: solid;
border-width: 1px;
}
#cards {
width: 64%;
}
#cards img {
float: right;
margin: 2px;
display: block;
}
!-- The box the images are dragged into--
<div id="draginto" ondragover="permitDrop(event)" ondrop="drop(event)">
</div>
!--The div with the cards in them--
<div id="cards">
<img src="https://via.placeholder.com/100x100?text=d8" draggable="true" id="dragto" ondragstart="drag(event)">
<img src="https://via.placeholder.com/100x100?text=dJ" draggable="true" id="dragto" ondragstart="drag(event)">
<img src="https://via.placeholder.com/100x100?text=dK" draggable="true" id="dragto" ondragstart="drag(event)">
<img src="https://via.placeholder.com/100x100?text=d10" draggable="true" id="dragto" ondragstart="drag(event)">
<img src="https://via.placeholder.com/100x100?text=dQ" draggable="true" id="dragto" ondragstart="drag(event)">
<img src="https://via.placeholder.com/100x100?text=d9" draggable="true" id="dragto" ondragstart="drag(event)">
</div>
我希望所有图像都可以拖到框中,而不仅仅是一个。
答案 0 :(得分:1)
dragto
的第一个元素。event.target
是否为#draginto
div,如果是,则移动拖动的项目,否则什么也不做:赞:
function drop(event) {
let target = event.target;
if(target.id === "draginto") {
event.preventDefault();
var data = event.dataTransfer.getData("Text");
target.appendChild(document.getElementById(data));
}
}