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>