gpt4 book ai didi

javascript - 如何使可拖动元素保持在同一个地方

转载 作者:行者123 更新时间:2023-11-28 02:34:31 26 4
gpt4 key购买 nike

如何让可拖动元素在被拖动后仍然显示在其源框上?

下面的脚本来说明一下:

function dragStart(ev) {
ev.dataTransfer.setData('text1', ev.target.id);
}

function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData('text1');
ev.target.appendChild(document.getElementById(data));
}

function allowDrop(ev) {
ev.preventDefault();
}
.boxarticle {
width: 200px;
height: 150px;
border: 1px solid blue;
margin: 0 0 10px 20
}

div#panier {
width: 150px;
height: 150px;
background-color: ;
border: 1px solid blue;
}
<!-- I want that image to remain here after I dragged it -->
<div class='boxarticle'>
<img src="https://cdn-images-1.medium.com/max/1200/1*QQvzwKk7rdC1JkY0XiPVUQ.png" draggable="true" id='image' data-price='9200' ondragstart="dragStart(event)" width=80 height=80>
</div>

<!-- where draggable element go in -->
<div id="panier" ondrop='drop(event)' ondragover="allowDrop(event)"> Drag and drop image here..but leave it in the source place </div>

最佳答案

你需要克隆它并给它一个新的id,否则它会假设“拖动”。

HTML5 drag and copy?

function dragStart(ev)
{
ev.dataTransfer.setData('text1',ev.target.id);
}

function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("text1");
var nodeCopy = document.getElementById(data).cloneNode(true);
nodeCopy.id = "randomId";
ev.target.appendChild(nodeCopy);
}

function allowDrop(ev)
{
ev.preventDefault();
}
.boxarticle { 
width:200px;height: 150px; border:1px solid blue;margin: 0 0 10px 20
}

div#panier {
width:150px;height: 150px;background-color: ; border: 1px solid blue;
}
<!-- I want that image to remain here after I dragged it -->
<div class='boxarticle'>
<img src="https://cdn-images-1.medium.com/max/1200/1*QQvzwKk7rdC1JkY0XiPVUQ.png" draggable="true" id='image' data-price='9200' ondragstart="dragStart(event)" width=80 height=80>
</div>

<!-- where draggable element go in -->
<div id="panier" ondrop='drop(event)' ondragover="allowDrop(event)"> Drag and drop image here..but leave it in the source place </div>

关于javascript - 如何使可拖动元素保持在同一个地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48359704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com