繁体   English   中英

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

[英]JavaScript functions not working onmouseover

当我尝试使用用 JavaScript 编写的函数来更改 ID 为“div4”的<div>块的样式时,我遇到了一个小问题。 我发现这段代码不能正常工作。 当我运行这些代码时,没有显示<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM