[英]Why does JS cross out the event variable when I try to give it to an function as an argument?
I copied this code from w3schools.我从 w3schools 复制了这段代码。 But the editor does cross out the word event.但是编辑确实划掉了事件这个词。
The code worked.该代码有效。 But I am not sure if I should change something because of the crossing out.但是我不确定我是否应该因为划掉而改变一些东西。
I want to make and application with this technique.我想用这种技术制作和应用。
Picture of the crossed out word被划掉的字的图片
<!DOCTYPE HTML>
<html>
<head>
<style>
#div1, #div2 {
float: left;
width: 100px;
height: 35px;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
</style>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<h2>Drag and Drop</h2>
<p>Drag the image back and forth between the two div elements.</p>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
<img id="drag1" src="https://cdn.pixabay.com/photo/2020/12/02/01/06/chipmunk-5795916__340.jpg" draggable="true" ondragstart="drag(event)" width="336" height="69">
</div>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</body>
</html>
You'd better not use inline functions in your HTML code, use addEventListener
for better code.您最好不要在 HTML 代码中使用内联函数,使用addEventListener
以获得更好的代码。
let dragged = null; const source = document.getElementById("draggable"); source.addEventListener("dragstart", (event) => { // store a ref. on the dragged elem dragged = event.target; }); const target = document.querySelectorAll(".dropzone"); target.forEach(function (item) { item.addEventListener("dragover", (event) => { // prevent default to allow drop event.preventDefault(); }); item.addEventListener("drop", (event) => { // prevent default action (open as link for some elements) event.preventDefault(); // move dragged element to the selected drop target if (event.target.className === "dropzone") { dragged.parentNode.removeChild(dragged); event.target.appendChild(dragged); } }); });
body { /* Prevent the user selecting text in the example */ user-select: none; } #draggable { text-align: center; background: white; }.dropzone { width: 100px; height: 40px; background: lightblue; margin: 10px; padding: 10px; }
<div class="dropzone"> <img id="draggable" src="https://cdn.pixabay.com/photo/2020/12/02/01/06/chipmunk-5795916__340.jpg" draggable="true" width="100" height="35"> </div> <div class="dropzone"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.