onmousemove 事件无法在 JavaScript 示例中传递事件数据

onmousemove Event is not able to pass event-data in JavaScript Example

在这个例子中,当我在 div 内移动鼠标时,我想显示鼠标当前位置的(x 和 y 坐标),但显示错误。为什么?

function fifa(ev){
  document.getElementById('div1').style.background = "cornsilk";
  document.getElementById('div1').innerHTML = (ev.clientX + " "  + ev.clientY);
}
div {
  height:200px; 
  width:200px; 
  border:2px solid #000; 
  background:green; 
  display:inline-block; 
  margin:20px;
}
<div id="div1" onmousemove="fifa(ev)">onmousemove</div>

您的错误是您试图传递未知变量 ev - 它不存在。你可以像他们一样传递(事件)at the site you usedmyFunction(event)

我强烈建议更改为 eventListener 并使用 MDN 而不是 w3schools

const div1 = document.getElementById('div1'); // cache the element
// only change colour once, using class
div1.addEventListener("mouseenter", function(e) {
  this.classList.add("silk")
})
div1.addEventListener("mouseleave", function(e) {
  this.classList.remove("silk")
})

div1.addEventListener("mousemove", function(e) {
  this.innerHTML = (e.clientX + " "  + e.clientY);
})
div {
  height:200px; 
  width:200px; 
  border:2px solid #000; 
  background:green; 
  display:inline-block; 
  margin:20px;
}
div.silk {background:cornsilk; }
<div id="div1">onmousemove</div>

供您参考,但请使用我的版本,这是您代码的固定版本。

注意我将事件传递给函数,它被提取为 ev - 不推荐,因为它已经在函数中可用

function fifa(ev){ // event passed as ev
  ev.target.style.background = "cornsilk"; // the div is the event target
  ev.target.innerHTML = (ev.clientX + " "  + ev.clientY); 
}
div {
  height:200px; 
  width:200px; 
  border:2px solid #000; 
  background:green; 
  display:inline-block; 
  margin:20px;
}
<div id="div1" onmousemove="fifa(event)">onmousemove</div>

在您的 HTML 中,只需将“ev”更改为事件即可。

   <div id="div1" onmousemove="fifa(event)">onmousemove</div>