为什么我得到'无法读取属性样式为null ';错误

Why I am getting "cannot read property style of null" error?

本文关键字:样式 属性 错误 null 读取 为什么      更新时间:2023-09-26

我不明白为什么它给

uncaught typeError: Cannot read property 'style' of null" at line 38

当我在所有div上移动鼠标指针时。每次我把指针移到div上,就会出现错误

请说明是什么问题。

var top = "p3";
function toTop(newTop) {
  var domTop = document.getElementById(top).style;
  var domNew = document.getElementById(newTop).style;
  domTop.zIndex = "0";
  domNew.zIndex = "10";
  top = document.getElementById(newTop).id;
}
.para1 {
  position: absolute;
  top: 10;
  left: 120;
  z-index: 0;
  border: solid;
  padding: 80;
  width: 300;
  background-color: aqua;
}
.para2 {
  position: absolute;
  top: 50;
  left: 150;
  z-index: 0;
  border: solid;
  padding: 80;
  width: 300;
  background-color: yellow;
}
.para3 {
  position: absolute;
  top: 100;
  left: 180;
  z-index: 0;
  border: solid;
  padding: 80;
  width: 300;
  background-color: red;
}
<div style="z-index: 10;" class="para1" id="p1" onmouseover="toTop('p1')">Frame One</div>
<div style="z-index: 5;" class="para2" id="p2" onmouseover="toTop('p2')">Frame Two</div>
<div style="z-index: 0;" class="para3" id="p3" onmouseover="toTop('p3')">Frame Three</div>

top是JavaScript中保留的标识符,因此您不能将其用作变量名。这意味着在这个函数中:

function toTop(newTop) {
    // here `top` points to `window`
    var domTop=document.getElementById(top).style;
    var domNew=document.getElementById(newTop).style;
    domTop.zIndex="0";
    domNew.zIndex="10";
    top=document.getElementById(newTop).id;
} 

top指向window对象,这就是为什么document.getElementById(top)返回null

您需要将readonly var top重命名为例如myTop -它会给出错误自窗口。Top是主窗口的句柄

var myTop = "p3";
function toTop(newTop) {
  var domTop = document.getElementById(myTop).style;
  var domNew = document.getElementById(newTop).style;
  domTop.zIndex = "0";
  domNew.zIndex = "10";
  myTop = document.getElementById(newTop).id;
}

我在官方文档中找不到top保留的,但它确实属于要避免的单词列表,因为它在浏览器实现中是只读的。

"top"是定义框架顶部的保留关键字,将变量名"top"替换为下面的内容。

var top1 = "p3";
function toTop(newTop) {
  var domTop = document.getElementById(top1).style;
  var domNew = document.getElementById(newTop).style;
  domTop.zIndex = "0";
  domNew.zIndex = "10";
  top1 = document.getElementById(newTop).id;
}