2016-11-14 61 views
0

我无法理解为什么它给为什么我得到“无法读取null的属性样式”错误?

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>

+0

@Fast蜗牛感谢您的编辑。我无法通过移动设备进行操作。 – Ankesh

+0

将**保留**和只读var'top'重命名为'myTop' - 它会给出错误,因为window.top是主窗口的句柄 – mplungjan

+0

@mplungjan谢谢。有效。 – Ankesh

回答

1

您需要的只读 VAR top重命名为例如myTop - 它给了错误,因为window.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是手柄保留在官方文档中,但它属于要避免的单词列表,因为它只是在浏览器实现中只读。

2

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

+0

请仅仅因为错字而关闭?我已经评论过这个 – mplungjan

+1

我不认为这是一种类型。 OP不知道'top'是一个保留字。 –

+1

@mplungjan我没有将有意编写的代码分类为拼写错误。这个问题很有价值。 – 4castle

0

“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; 
} 
+0

你的代码中有两件事:** 1 /.**没有什么叫做'top2',那么,你应该把'top1'重命名为另一个名字吗? ** 2 /.**你需要更新行'top = document.getElementById(newTop).id;' –

+0

谢谢。更正 –

相关问题