【问题标题】:How to detect the div where we in using javascript drag and drop如何检测我们使用javascript拖放的div
【发布时间】:2018-04-17 02:22:50
【问题描述】:

这是我的 JavaScript 代码 `

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

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

    function drop(ev) {
        ev.preventDefault();
        var data = ev.dataTransfer.getData("Text");
        var classs = ev.dataTransfer.getData("class");
        if(data === "body") {
            document.getElementById('div1').className = '';
            document.getElementById('div1').classList.add(classs);
        }
        if(data === "table"){
            document.getElementById('myTable').className = '';
            document.getElementById('myTable').classList.add(classs);
        }
        if(data === "font"){
            document.getElementById('myTable').classList.add(classs);
        }
    }`

如您所见,我只是根据我在要拖放的元素中设置的 id 获取 div,如何检测拖放时我们在哪里元素,所以我不需要使用 document.getElementById再次

【问题讨论】:

  • drop内引用ev.target

标签: javascript drag-and-drop drag detection


【解决方案1】:

你的意思是“ondragenter”还是“ondrop”?

<div id='div1' ondrop="drop1(event)></div>
<script>
function drop1(event) {
event.preventDefault();
event.target.style.backgroundColor = "lightblue";
}
</script>

【讨论】:

  • 在 drop 事件上,所以当它被丢弃时它会检测到什么元素被丢弃并添加类到它
  • 它和我的代码一样,我不想使用'if'条件,但我希望它自动检测元素,所以我不需要添加 div1 等
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-15
  • 1970-01-01
  • 1970-01-01
  • 2010-11-05
  • 1970-01-01
相关资源
最近更新 更多