gpt4 book ai didi

javascript - 拖放 html 元素

转载 作者:行者123 更新时间:2023-12-03 12:13:12 25 4
gpt4 key购买 nike

我有一个可以拖动的div。如果它被拖动,我想将其文本添加到鼠标,离开鼠标后我想显示一些菜单,例如复制。

我已经尝试过这个:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style>
#div1
{
width:350px;
height:70px;
padding:10px;
border:1px solid #aaaaaa;
}
</style>
<script>

function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}

function drop(ev)
{
ev.preventDefault();
//console.log(ev.dataTransfer);
//var data=ev.dataTransfer.getData("Text");
//ev.target.appendChild(document.getElementById(data));
alert(ev.target.id);

}

function allowDrop(ev){
ev.preventDefault();
}

</script>
</head>
<body>


<a draggable="true" ondragstart="drag(event)" id="drag-id" >dragme</a>

<div id="div1" style="border: solid 1px; width:40px; height:40px;" ondrop="return drop(event)" ondragover="allowDrop(event)"></div>

</body>
</html>

最佳答案

<强> SOLUTION 使用假拖放。

这里的问题是它只能在 body 元素内部工作。

var fakeDrag = {
setup: function(){
fakeDrag.el = document.createElement('span');
fakeDrag.el.style['pointer-events'] = 'none';
fakeDrag.el.style['position'] = 'absolute';
fakeDrag.el.style['display'] = 'none';
fakeDrag.el.textContent = 'dragging';
document.body.appendChild(fakeDrag.el);
},
dragging: false,
drag: function(event){
if(event.target.classList.contains('drag')){
fakeDrag.dragging = true;
fakeDrag.source = event.target;
fakeDrag.el.style['display'] = 'inline';
}
},
dragmove: function(event){
fakeDrag.el.style['top'] = ++event.clientY+'px';
fakeDrag.el.style['left'] = ++event.clientX+'px';
},
drop: function(event){
if(event.target.classList.contains('drop') && fakeDrag.dragging){
event.target.textContent = fakeDrag.source.textContent;
}
fakeDrag.dragging = false;
fakeDrag.el.style['display'] = 'none';
}
};
fakeDrag.setup();

关于javascript - 拖放 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24858164/

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