HTML5拖放访问属性

HTML5 Drag and Drop access Attribute

本文关键字:属性 访问 拖放 HTML5      更新时间:2023-09-26

我正在研究拖放,以便在一个项目上实现,正如你在这个CodePen上看到的那样,它使用HTML5工作,但我需要它在我的项目上使用更复杂,特别是能够访问拖动对象的数据属性。

这是HTML

<section class="sectionOne">
    <div draggable="true" class="sec-one-div" ondrag="dragCheck(event);" ondragstart="dragStart(event);" data-somedata="300">
        <p>This is section one</p>
    </div>
    </section>
<section class="sectionTwo" ondrop="drop(event);" ondragover="dragover(event);" id="secTwo">
    <p>This is section two</p>
</section>
<section class="sectionThree" >
    <p>This is section three</p>
</section>

JS

function dragCheck(ev) {
    console.log("im dragging");
}
function dragStart(ev) {
    console.log('drag start');
    ev.dataTransfer.setData("text", "this is some text");
}
function dragover(ev) {
    ev.preventDefault();
    // Set the dropEffect to move
    ev.dataTransfer.dropEffect = "move"
}
function drop(ev) {
    ev.preventDefault();
    console.log('drop');
    var data = ev.dataTransfer.getData('text');
    $('#secTwo').append('hahaaha');
}

我需要访问被拖动的div的"data-somedata"属性(在我的项目中,我需要5个,但现在需要1个),这样我就可以在另一个元素上附加正确的值。我该怎么做?

文件对我来说不清楚我应该用什么来获得这个结果,感谢所有的帮助。如果需要更多信息,请告诉我。

事件包含目标拖动元素,因此可以使用获取该元素的属性

function dragCheck(ev) {
  console.log("im dragging");
  console.log(ev.target.getAttribute("data-someinfo"));
}

或者使用jQuery:

function dragCheck(ev) {
  console.log("im dragging");
  console.log($(ev.target).attr('data-someinfo'));
}