【问题标题】:2 divs positioned absolute, one is blocking the other2 个 div 绝对定位,一个挡住另一个
【发布时间】:2014-09-08 16:52:48
【问题描述】:

我有 2 个 div,宽度相同,绝对定位,在页面上水平和垂直居中。

每个 div 都包含一个链接。但是只有一个链接是可点击的。我需要两个链接都是可点击的。

这是我的jsfiddle

<div class="button"> <a href="http://www.google.com" target="_blank">button</a> </div>
<div class="arrows"> <a href="http://www.google.com" target="_blank">arrows</a> </div> 

.button, .arrows {
 position: absolute;
 top: 0;
 bottom: 0;
 left: 0;
 right: 0;
 width: 520px;
 height: 240px;
 margin: auto !important; 
 border: 1px solid #000;
}
.button { z-index: 999; }
.arrows { text-align: center; z-index:99999; }
.button a { border: 1px solid red; }
.arrows a { border: 1px solid yellow; }

任何提示将不胜感激。

谢谢。

【问题讨论】:

  • 不要将它们放在一起。我不确定您要做什么,但这种 HTML/CSS 可能是错误的方法。
  • 为什么要将 div 放置在绝对位置?为什么不将两个链接放在一个 div 中?在这里解释你要做什么

标签: html css position center absolute


【解决方案1】:

问题是divs 都占据了整个盒子的空间,所以不可能两者都可以点击。

解决方案是有一个单独的 div 容器,即盒子,并让按钮和箭头 as 成为容器内的较小元素:

<div class="container">
    <a class="button" href="http://www.google.com" target="_blank">button</a>
    <div class="arrow"><a href="http://www.google.com" target="_blank">arrows</a></div>
</div>

为了保持相同的外观,我们需要一个箭头容器,将箭头的链接居中。按钮链接将是position: absolute,以允许两个链接存在于同一行。

.container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 520px;
    height: 240px;
    margin: auto !important;
    border: 1px solid #000;
}
.arrow {
    display: inline-block;
    width: 100%;
    text-align: center;
}
.arrow a {    
    border: 1px solid yellow;
}
.button {
    border: 1px solid red;
    position: absolute;
}

查看更新后的Fiddle

【讨论】:

    【解决方案2】:

    问题源于您将 div 设置为相同的宽度和高度,第二个 div 覆盖了第一个 div,因此点击不会失败。

    如果你想要那个边框,你需要一个父 div。

    JSFiddle http://jsfiddle.net/6qXAm/

    <div class="parent">
    <div class="button"> <a href="http://www.google.com" target="_blank">button</a> </div>
    <div class="arrows"> <a href="http://www.google.com" target="_blank">arrows</a> </div>    
    </div>
    
    .parent {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        width: 520px;
        height: 240px;
        margin: auto !important; 
        border: 1px solid #000;
    }
    

    【讨论】:

    • 效果很好,但是无法将所有内容包装在父 div 中,因为箭头 div 正在页面上的其他位置动态加载。
    • 为什么不能将箭头div动态添加到父容器中?
    【解决方案3】:

    好的,我将发布另一个答案,因为这个答案采用了完全不同的方法。

    CSS 允许使用属性pointer-events,它允许您指定元素是否可以成为鼠标事件的主题。

    在这种情况下,您不希望 .arrows div 支持鼠标事件,但您确实希望 .arrows a 链接元素支持。所以你会使用:

    .arrows { pointer-events: none; }
    .arrows a { pointer-events: all; }
    

    这将允许点击链接,但对于 div 的其余部分,将强制鼠标事件(点击)通过到它下面的元素(在这种情况下,@ 987654329@链接)。

    这是一种 hack,但效果很好。
    请参阅 Fiddle

    【讨论】:

    • 我很想用这个,但是 IE 不配合。
    • 没错,如果您查看browser compatibility 中的指针事件,IE 需要为 11 或更高版本。
    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 2012-01-15
    • 2011-04-09
    • 1970-01-01
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多