2011-11-11 38 views
2

我有以下代碼用於堆疊元素,並將光標放在elemnt元素頂部。 這是代碼..它由於某種原因不工作。段落顯示,但將鼠標移到它們上面時,沒有任何反應。使用Javascript堆疊元素

<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> 

回答

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

+0

'oldTopStyle [「z-index」] =「0」;'也可以。 – Miscreant

2

代碼

top=document.getElementById(top).id; 

應該

top = newTop; 

及其

zIndex not z-index