javascript - div标签的分层问题

标签 javascript css html layer

假设我有两个 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/

相关文章:

html - 更高分辨率的媒体查询

python - 在 HTML/.format() 中使用 Python 变量

javascript - 我的 Protractor 脚本错误 - 需要对象

jquery - 动画系列图像 block 彼此独立

javascript - 显示瞬时选中的单选按钮的数量

css - CSS:位置:固定和水平滚动

html - 如何确保 flexbox 小于周围的元素

html - 在对齐表单中心时将跨度字段向左对齐

javascript - 如何读取 extjs 数据存储

javascript - 如何在 WebForms 中格式化 SelectList 的 AJAX 数据?