底层元素无法点击

时间:2017-11-16 15:32:34

标签: html css html5 twitter-bootstrap css3

我必须在两个不同的(bootstrap' s)行中渲染两个元素,底部的一个必须在最顶层的后面。我无法理解为什么底层的东西没有捕捉指针事件。



.smaller-square {
  width: 50px;
  height: 50px;
  background-color: yellow
}

.bigger-square {
  width: 100px;
  height: 100px;
  background-color: green
}

.overlay {
  z-index: 0;
}

.underlay {
  z-index: -1;
  position: relative;
  top: -5px;
  left: 0px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row overlay">
  <div class="smaller-square" onclick="alert('yellow');">
  </div>
  </div>
  <div class="row underlay">
  <div class="bigger-square" onclick="alert('green');">
  </div>
  </div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

这是因为绿色的z-index: -1位于bodyhtml元素之后。您的活动可能正由body捕获。尝试添加包装并在其上设置z-index或将z-index应用于容器。

&#13;
&#13;
.smaller-square {
  width: 50px;
  height: 50px;
  background-color: yellow
}

.bigger-square {
  width: 100px;
  height: 100px;
  background-color: green
}

.overlay {
  z-index: 0;
}

.underlay {
  z-index: -1;
  position: relative;
  top: -5px;
  left: 0px;
}

.container {
  position: relative;
  z-index: 0;
}
&#13;
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row overlay">
  <div class="smaller-square" onclick="alert('yellow');">
  </div>
  </div>
  <div class="row underlay">
  <div class="bigger-square" onclick="alert('green');">
  </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

向包含元素position: relative声明.container,以便您可以通过声明z-index属性来应用堆叠上下文。

您甚至不需要在兄弟元素z-index上声明的.overlay属性,因为它不是“定位元素” - 也就是说它位于static而不是绝对(绝对和固定)或相对。因此z-index不适用。

.smaller-square {
  width: 50px;
  height: 50px;
  background-color: yellow
}

.bigger-square {
  width: 100px;
  height: 100px;
  background-color: green
}

.overlay {
/* redundant unless you declare a position property for this element
   that is not "static" - which is the default positioning for any element */
  z-index: 0; 
}

.underlay {
  z-index: -1;
  position: relative;
  top: -5px;
  left: 0px;
}


/* Additional */

.container {
  position: relative;
  z-index: 1;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row overlay">
    <div class="smaller-square" onclick="alert('yellow');">
    </div>
  </div>
  <div class="row underlay">
    <div class="bigger-square" onclick="alert('green');">
    </div>
  </div>
</div>