当我尝试使用用 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/