使用Javascript堆叠元素

时间:2011-11-11 17:56:21

标签: javascript html css

我有以下代码用于堆叠元素,并将光标放在元素上,该元素位于顶部。 这是代码..由于某种原因它不起作用。显示段落,但在将鼠标移到它们上时没有任何反应。

<html>
<head>
<title>Stacking</title>
</script>
<style type="text/css">
.layer1Style
{
position: absolute;
top:50pt;
left:50pt;
background-color:red;
z-index:0;
}
.layer2Style
{
position: absolute;
top:75pt;
left:75pt;
background-color:green;
z-index:0;
}
.layer3Style
{
position: absolute;
top:100pt;
left:100pt;
background-color:blue;
z-index:10;
}
</style>

<script type="text/javascript">
var top="layer3";

function mover(newTop)
{
var oldTopStyle=document.getElementById(top).style;
var newTopStyle=document.getElementById(newTop).style;
oldTopStyle.z-index="0";
newTopStyle.z-index="10";
top=document.getElementById(top).id;
}
</script>
</head>

<body>
<div class="layer1Style" id="layer1" onmouseover="mover('layer1')">
<p>This is my first paragraph</p>
</div>
<div class="layer2Style" id="layer2" onmouseover="mover('layer2')">
<p>This is my second paragraph</p>
</div>
<div class="layer3Style" id="layer3" onmouseover="mover('layer3')">
<p>This is my third paragraph</p>
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:7)

您无法在JavaScript中使用z-index,因为它被解释为z minus index。请改用zIndex

function mover(newTop)
{
    var oldTopStyle = document.getElementById(top).style;
    var newTopStyle = document.getElementById(newTop).style;
    oldTopStyle.zIndex = "0";  // "zIndex", not "z-index"
    newTopStyle.zIndex = "10"; // "zIndex", not "z-index"
    top = document.getElementById(top).id;
}

(并且还要注意,您不能将top用作全局变量,因为它已被声明为只读属性window.top

答案 1 :(得分:2)

代码

top=document.getElementById(top).id;

应该是

top  = newTop;

及其

zIndex not z-index