0
这是一个堆叠文本元素的简单示例。函数外部变量的混淆
HTML:
<html>
<head>
<title>Program 2</title>
<link rel="stylesheet" type="text/css" href="ex2.css">
<script type="text/javascript" src="ex2.js"></script>
</head>
<body>
<p class="box" id="para1" onmouseover="display('para1');">
This is a paragraph.
</p>
<p class="box" id="para2" onmouseover="display('para2');">
This is a paragraph.
</p>
<p class="box" id="para3" onmouseover="display('para3');">
This is a paragraph.
</p>
</body>
</html>
CSS:
.box {
border: 1px solid black;
width: 500px;
position: absolute;
}
#para1 {
font-size: 20pt;
color: white;
background: red;
top: 150px;
left: 150px;
}
#para2 {
font-size: 20pt;
color: white;
background: blue;
top: 200px;
left: 200px;
}
#para3 {
font-size: 20pt;
color: white;
background: green;
top: 250px;
left: 250px;
}
JS:
var defaultTop = 'para3';
function display(select)
{
newTop = document.getElementById(select)
oldTop = document.getElementById(defaultTop);
oldTop.style.zIndex = "0";
newTop.style.zIndex = "10";
defaultTop = select;
}
当我把var defaultTop = 'para3';
函数内部,仅para2
和para3
分别作为我移动所显示鼠标悬停,但不是para1
。但是当我把var defaultTop = 'para3';
放在函数的外面时,所有的para分别显示出来。为什么?
尝试阅读: 1. http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript/500459#500459 2. http:// stackoverflow .com/questions/111102/how-do-javascript-closures-work – DCrystal 2014-08-31 18:02:13
因为函数的范围与全局程序不同。 – 2014-08-31 18:02:36