javascript代码和zindex

时间:2013-04-24 17:13:38

标签: javascript html z-index

我遇到使用javascript更改z-index的问题,任何人都可以帮助我解决我的错误,

我想要做的是,一旦点击一个按钮,它就会出现在另一个盒子的顶部,但它似乎不起作用。

function toggleupload(){
            var but = document.getElementById('picbutton').innerHTML;
            if (but == "Change Picture"){
                            document.getElementById('picbutton').innerHTML = "Hide upload box";
                            document.getElementById('uploadbox').style.zIndex = 2;
                            document.getElementById('profilebasic').style.zIndex = 1;
            }
            if (but == "Hide upload box"){
                            document.getElementById('picbutton').innerHTML = "Change Picture";
                            document.getElementById('uploadbox').style.zIndex = 1;
                            document.getElementById('profilebasic').style.zIndex = 2;
            }

}




#profilebasic{
            width:300px;
            height:300px;
            z-index:2;
            background-color:#0F0;

}
#uploadbox {
            position:absolute;
            top:0px;
            left:0px;
            width:300px;
            height:300px;
            z-index:1;
            background-color:#F00;

}
#uploadbo{
            text-align:center;
            width:300px;
            height:300px;
            z-index:3;

}




<div id="uploadbo">
<div id="profilebasic">
</div>
<div id="uploadbox">
</div>
<button  onclick="toggleupload();" id="picbutton">Change Picture</button>
            </div>

2 个答案:

答案 0 :(得分:4)

z-index属性only works on positioned elements,因此您需要在profilebasic上明确设置位置,如:

#profilebasic {
    width:300px;
    height:300px;
    z-index:2;
    background-color:#0F0;
    position:absolute;
}

<强> jsFiddle example

(请注意,我还必须在你的按钮上设置一些CSS,否则它会在你定位的div下结束。)

答案 1 :(得分:0)

由于uploadbox已经在前面开始,我假设你要交换它们。

基于z-index规则,绝对定位的div仍将出现在非绝对定位的div前面,除非其z-index值为负。

也就是说,对你想要落后的盒子使用负z-index。

http://jsfiddle.net/X54gr/