Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - Event is undefined when using dragstart

I'm trying to make elements in a list draggable but I'm running into an issue that I can't figure out. My code below follows a general format I've seen in some tutorials.

My list of draggable elements is formatted as such:

function startDrag(e) {
    e.dataTransfer.effectAllowed = 'move';
    console.debug(e);
    e.dataTransfer.setDragImage(e.target, 0, 0);
    return true;
}
<ul>
<li class="drag" draggable="true" ondragstart="startDrag(e)"><img src="/my/image/path.svg"></li>
<li class="drag" draggable="true" ondragstart="startDrag(e)"><img src="/my/image/path2.svg"></li>
</ul>
question from:https://stackoverflow.com/questions/66052830/event-is-undefined-when-using-dragstart

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Inline event handling attributes are not passed a reference to a DOM event and that's why your argument is undefined.

Don't use inline HTML event attributes to hook up events. That's a 25+ year old technique that just will not die.

Follow modern standards and use .addEventListener() which will automatically be passed a reference to the DOM event that triggered the handler.

document.querySelectorAll(".drag").forEach(function(item){
  item.addEventListener("dragstart", startDrag);
});

function startDrag(e) {
    console.log("Drag started! Event was: ", e.type);
}
<ul>
  <li class="drag" draggable="true">Drag me.</li>
  <li class="drag" draggable="true">No, drag me!</li>
</ul>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...