JavaScript 函数在鼠标悬停时不起作用

标签 javascript html onmouseover

当我尝试使用用 JavaScript 编写的函数来更改 <div> 的样式时,我遇到了一个小问题。 block ,其 ID 为“div4”。我发现这段代码不能正常工作。 <div>当我运行这些代码时没有显示。问题出在哪里?

function togreen() {
  document.getElementById('div4').style.width = '200px';
  document.getElementById('div4').style.height = '200px';
  document.getElementById('div4').style.backgroundColor = 'green';
}

function tored() {
  var DIV4 = document.getElementById('div4');
  DIV4.style.width = '100px';
] DIV4.style.height = '100px';
DIV4.style.backgroundColor = 'red';
}
window.onload = function() {
  var DIV = document.getElementById('div4');
  DIV.onmouseover = togreen;
  DIV.onmouseout = tored;
};
<div id="div4"></div>

最佳答案

首先,代码中有一个错误的],导致语法错误。
(看起来像打字错误。)

其次,元素没有初始宽度或高度。它不会注册任何“mouseover”或“mouseout”事件,因为没有什么可以悬停的。

下面,我给了它一些初始大小。
我还在 window.onload 中定义了一次 DIV4 并引用了 this从处理程序中。

function togreen() {
  this.style.width = '200px';
  this.style.height = '200px';
  this.style.backgroundColor = 'green';
}

function tored() {
  this.style.width = '100px';
  this.style.height = '100px';
  this.style.backgroundColor = 'red';
}

window.onload = function() {
  var DIV4 = document.getElementById('div4');
  DIV4.onmouseover = togreen;
  DIV4.onmouseout = tored;
}
#div4 {
  width: 50px;
  height: 50px;
  background-color: lightgray;
}
<div id="div4"></div>

关于JavaScript 函数在鼠标悬停时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48697361/

相关文章:

javascript - 调用时如何获取函数名?

javascript - 如何使用更多 "expect"函数扩展 frisby.js?

javascript - 获取对象值时引用变量

javascript - 执行带有仅当任何其他事件发生时才会发生的事件的 JavaScript

php - WordPress 编辑器删除 div 属性

css - 使用 css transform :scale(x); 时设置 hitbox

html - 将淡入淡出过渡添加到 onmouseout 和 onmouseover

javascript - 使用 Jquery 遍历列表

html - 使用 NgFor 代替 HTML