假设我有两个Div层
<div id="div1"> One </div>
<div id="div2"> Two </div>我要他们两个都重叠
当我点击按钮时,我希望Div1层出现在背景中,顶层应该变成Div2。
如何通过JavaScript实现?
发布于 2011-01-22 23:58:41
如果使用CSS设置z-index,那么您需要获取元素的计算样式,因此直接获取element.style.zIndex将不起作用。由于这在IE中的实现方式与在其他浏览器中不同,因此让我们创建一个函数来获取计算样式:
var getCompStyle = function( id ) {
var curStyle;
if (window.getComputedStyle) {
curStyle = window.getComputedStyle(document.getElementById( id ), null);
} else {
curStyle = document.getElementById( id ).currentStyle;
}
return curStyle;
};一旦我们有了这个函数,我们就可以将z-index应用于相应的按钮单击处理程序:
document.getElementById('switch').onclick = function(e) {
var div1style = getCompStyle( 'div1' );
var div2style = getCompStyle( 'div2' );
var switcher = div1style.zIndex;
document.getElementById('div1').style.zIndex = div2style.zIndex;
document.getElementById('div2').style.zIndex = switcher;
};我创建了a fiddle example here (link)来演示。
发布于 2011-01-22 23:46:36
在CSS中使用"z-index“参数控制垂直位置。你可以通过javascript访问元素的"style“参数来设置它。
这里有一个完整的例子,注释指出了要注意的棘手之处:
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.container {
/* Needs explicit positioning for "absolute" positioning of
child elements to work properly */
position: relative;
/* Need to set height, because absolute-positioned child elements take up no space */
height: 50px;
}
#div1, #div2 {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 50px;
/* without a background color, you'll see div1 through div2. */
background-color: white;
/* border makes it easier to see while testing */
border: 1px solid red;
}
</style>
<script type='text/javascript'>
function swapDivs() {
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
// swap zIndex values.
var temp = div1.style.zIndex;
div1.style.zIndex = div2.style.zIndex;
div2.style.zIndex = temp;
}
</script>
</head>
<body>
<div class='container'>
<div id="div1" style='z-index: 0;'> One </div>
<div id="div2" style='z-index: 1;'> Two </div>
</div>
<input id='switch' type='button' value='switch' onclick='swapDivs();' />
</body>
</html>发布于 2011-01-22 23:45:16
所以,根据我所读到的,你只是想展示一个,隐藏另一个?你可以用css中的display来做这件事。这里有一种你可以做到的方法。
<div id="div1">One</div>
<div id="div2" style="display:none;">Two</div>
<button onClick="change_layer()">Change the Layer</button>
function change_layer(){
document.getElementById("div1").style.display = "none";
document.getElementById("div2").style.display = "block";
}您也可以使用JQuery,但如果这是您需要做的全部工作,则可能不需要JQuery。如果你真的想把它们分层,你必须在css中使用z-index。
https://stackoverflow.com/questions/4768695
复制相似问题