【问题标题】:Add the Ability to click on buttons in DIV that is behind other DIV添加能够单击其他 DIV 后面的 DIV 中的按钮
【发布时间】:2014-08-29 10:30:27
【问题描述】:

我有一个位于 div 上的按钮,位于另一个 div 后面。第二个 div 通过使用 css 与第一个重叠:

position: absolute;

因此该按钮不可点击。有什么办法可以让它像普通按钮一样可点击?

示例:jsfiddle

HTML:

<div class="stack">
    <div class="background" onclick="alert('background clicked');">
        <button onclick="alert('bg-button clicked');" style="left:65px; top:65px; position: absolute;">This is a background button</button>
        <div class="card">
            <button onclick="alert('card-button clicked');">This is a card button</button>
            <textarea style="left:100px; top:100px; position: absolute;">This is a card textarea</textarea>
        </div>
    </div>
</div>

CSS:

body {
    background-color: blue;
}
.stack {
    width: 320px;
    height: 240px;
    position: absolute;
    top: 50%;
    left: 50%;
    background-color: white;
    margin-top:-120px;
    margin-left:-160px;
}
.background {
    width: 320px;
    height: 240px;
    background-image:url('http://www.userlogos.org/files/logos/ps1d3r/apple-black-i.png');
    top:0px;
    left:0px;
    position: absolute;
}
.card {
    pointer-events:none;
    width: 320px;
    height: 240px;
    background-image:url('http://2.bp.blogspot.com/-OIHQM4x8l0U/UEiDLQyiTRI/AAAAAAAAHFs/i1a6rkqQ8tQ/s320/floral+swirl.png');
    top:0px;
    left:0px;
    position: absolute;
}

【问题讨论】:

    标签: html css button click


    【解决方案1】:

    给按钮一个积极的z-index

    button {
        position: absolute;
        z-index: 1;
    }
    

    【讨论】:

    • 这个问题是按钮出现在我的背景 DIV 图像上方。有什么办法可以让它保持在图片后面并使其可点击?
    【解决方案2】:

    您可以在.card 上使用pointer-events:none;。这将禁用.card div 上的点击事件,用户可以点击它后面的按钮。 More info here (MDN)

    缺点是它还会禁用 textarea 和“卡片按钮”,因此您必须更改 HTML 并将 textarea 和卡片按钮移出.card div,以便它们仍然可以点击

    DEMO

    【讨论】:

    • 但是我不能点击另一个按钮?
    • 听起来需要从根本上重新考虑 HTML。
    • @user2370460 我已根据您的要求更新了答案
    • @Paulie_D 其实这很简单,OP 只需要将 textarea 和按钮移出 .card div 并使用 pointer-events:none; 不需要其他 CSS。
    • 这行得通。请务必注意,您设置了指针事件:无;专门在父 div 上,但不在子 div 上(如按钮,您可能需要显式添加 div &gt; * {pointer-events: auto;} 或类似内容),您仍然可以单击它们,还可以单击周围的 div 到它后面的按钮.最后,可能还值得一提的是,这对旧版浏览器存在兼容性问题(如果您的目标人群说您应该关心这些事情)。
    【解决方案3】:

    在这种情况下使用z-index

    <button onclick="alert('bg-button clicked');" style="left:65px; top:65px; position: absolute; z-index:1;">This is a background button</button>
    

    DEMO

    这会将深度场中的元素置于高于其他所有元素的位置。数字越大,堆栈顺序越高。

    z-index: 1;
    

    不过,z-index 需要定位,例如 position: absolute;position: relative;

    Read a great article about Z-Index here.

    【讨论】:

    • 这个问题是按钮出现在我的背景 DIV 图像上方。有什么办法可以让它保持在图片后面并使其可点击?
    猜你喜欢
    • 2017-04-12
    • 2017-03-09
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多