如何在低不透明度的图像上显示隐藏的div

时间:2016-06-26 18:31:15

标签: html css

假设我有一张图片。当我将光标放在图像上时,我想在图像上显示具有相同宽度和相同高度的图像。 div的背景将包含黑色,不透明度.6。首先,我在下面包含了一个代码,但它无法正常工作。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <style>
.under_menu{
  width: 400px;
  height: 400px;
  background-color: black;
  opacity: .5;
  position: absolute;
  display: none;
}
.image:hover .under_menu{
  display: block;
  margin-top: -20px;
}
.main_menu{
  position: relative;
  display: inline-block;
}

</style>
  </head>`
  <body>
     <div class="main_menu">
       <img src="com22.jpg" class="image" width="400" height="400" alt="" />
       <div class="under_menu"></div>
     </div>
  </body>
</html>

2 个答案:

答案 0 :(得分:2)

top: 0; left: 0; pointer-events: none提交给.under_menu并将.image:hover .under_menu更改为.image:hover ~ .under_menu,它会正常工作。

~是兄弟选择器,这是必需的,因为.under_menu不是.image的孩子,pointer-events: none使其不闪烁,因为它从.under_menu中删除指针事件。

这也可以使用伪元素完成,在我的2:nd示例中显示。

&#13;
&#13;
.under_menu{
  top: 0;
  left: 0;
  width: 300px;
  height: 300px;
  background-color: black;
  opacity: .5;
  position: absolute;
  display: none;
  pointer-events: none;
}
.image:hover ~ .under_menu{
  display: block;
}
.main_menu{
  position: relative;
  display: inline-block;
}
&#13;
<div class="main_menu">
  <img src="http://lorempixel.com/400/400/city" class="image" width="300" height="300" alt="" />
  <div class="under_menu"></div>
</div>
&#13;
&#13;
&#13;

2:nd sample(使用伪元素)

&#13;
&#13;
.main_menu {
  position: relative;
  display: inline-block;
}
.main_menu:hover::after {
  content: '';
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: black;
  opacity: .5;
  position: absolute;
}
&#13;
<div class="main_menu">
  <img src="http://lorempixel.com/400/400/city" class="image" width="300" height="300" alt="" />
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

问题是.image:hover .under_menu永远不会有效,因为这会告诉CSS一个人将.image一个悬停在其中的孩子&#34; .under_menu应该做一些事情,但.under_menu不是孩子的兄弟,所以你必须做.image:hover + .under_menu

或者,如果你内心没有任何其他元素,你可以.main_menu:hover .under_menu

https://jsfiddle.net/up4oswLm/