HTML5 DnD,事件处理程序和类索引

时间:2015-02-09 20:00:59

标签: html5 events

无论如何都要获得触发了一个' dragstart'事件处理程序,来自该处理程序?我需要这些信息,以便我可以设置一个带有该索引的数据传输对象,以便稍后在“删除”中使用。事件处理程序。

<div id="div1">
    <div draggable="true"  class="thetiles">goo</div>
    <div draggable="true"  class="thetiles">hoo</div>
    <div draggable="true"  class="thetiles">zoo</div>
</div>

function registerSource() {
    var matches = document.querySelectorAll('div.thetiles');
    for (var i = 0; i < matches.length; i++) {
        matches[i].addEventListener('dragstart', handleDragStart, false); 

    }
}


function handleDragStart(e) {
  this.style.opacity = '0.3';
  e.dataTransfer.effectAllowed = 'move';
  /* need to get index of the class element that triggered this
  for the following data transfer object set */
  e.dataTransfer.setData('text/html', ????);
}

1 个答案:

答案 0 :(得分:0)

function registerSource() {
    var matches = document.querySelectorAll('div.thetiles');
    for (var i = 0; i < matches.length; i++) {
        matches[i].addEventListener('dragstart', handleDragStart, false); 
        matches[i].addEventListener('dragstart', handleDragEnd, false); 
    }
}

var index
function handleDragStart(e) {
  this.style.opacity = '0.3';

  // Here is your index
  index = Array.prototype.indexOf.call(e.target.parentNode.children, e.target)

  e.dataTransfer.effectAllowed = 'move';
  //e.dataTransfer.setData('text/html', ????);
}

function handleDragEnd(e) {
 e.target.style.opacity = "";
    console.log(index) // Quick confirmation
  }

registerSource()

jsfiddle

这是你需要的吗?