假设我有两个 Div 层
<div id="div1"> One </div>
<div id="div2"> Two </div>
我希望它们都重叠
当我点击按钮时 我希望 Div1 层进入背景,顶层应成为 Div2。
我如何通过 JavaScript 实现它?
最佳答案
如果 z-index
是用 CSS 设置的,那么你需要获取元素的计算样式,所以直接获取 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)进行演示。
关于javascript - div标签的分层问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4768695/