javascript代码和zindex(javascript code and zindex)
我在使用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>I am having problems with getting the z-index to change using javascript can any one help me on where I am going wrong,
what I am trying to do is have a box appear on top on another box once a button is clicked but it does not seem to work.
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>最满意答案
z-index属性仅适用于定位元素 ,因此您需要在profilebasic上显式设置位置,如:
#profilebasic { width:300px; height:300px; z-index:2; background-color:#0F0; position:absolute; }jsFiddle示例
(请注意,我还必须在你的按钮上设置一些CSS,否则它会在你定位的div下结束。)
The z-index property only works on positioned elements, so you need to explicitly set the position on profilebasic like:
#profilebasic { width:300px; height:300px; z-index:2; background-color:#0F0; position:absolute; }jsFiddle example
(note that I also had to set some CSS on your button otherwise it would have ended up under your positioned divs.)
更多推荐
发布评论