如何使用jQuery切换隐藏的叠加层

时间:2018-02-07 11:45:49

标签: javascript jquery html css

我正在处理一个page,它将包含多个工作示例,并且希望能够在鼠标悬停在图像上时在每个元素上显示隐藏的叠加层。我有两个样本。显示隐藏叠加层的初始悬停当前显示两者上的叠加层。我想将显示限制为单个元素,然后在鼠标移出或单击叠加层时隐藏叠加层。

这是HTML:

          <div class="project col-sm-6">
           <a class="project_link" href="/our-work/project/{url_title}">
              <img src="/images/tmp-website-1.jpg" alt="replace" class="img-fluid" />
            </a>
            <div class="overlay" style="display: none;">
                <div class="text">
                <h3>Project Title</h3>
                <p>Project Summary</p>
                <p class="view"><a href="/our-work/project/">VIEW</a></p>
                </div>
            </div><!-- overlay -->
        </div><!-- project -->

CSS:

.project { 
    position: relative;
    width: 95%;
    height: auto;
    padding: 0;
    overflow: hidden;
    }

.overlay { 
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background-color: #fff;
    opacity: .9;
 }

.text { width: 75%; height: 30%; margin: 50px auto; text-align: center; } 

jQuery:

$( '.project_link' ).hover(function() {
  $( '.overlay' ).show( );
});
$('.overlay').click(function() {
  $( '.overlay' ).hide( );
})

2 个答案:

答案 0 :(得分:2)

使用jquery没什么意义。只需使用纯CSS。

.project:hover .overlay{
  display:block;
}

.overlay {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background-color: #fff;
  opacity: .9;
  display:none;
}

<强>演示

.project {
  position: relative;
  width: 95%;
  height: auto;
  padding: 0;
  overflow: hidden;
}

.project:hover .overlay{
  display:block;
}

.overlay {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  background-color: #fff;
  opacity: .9;
  display:none;
}

.text {
  width: 75%;
  height: 30%;
  margin: 50px auto;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="project col-sm-6">
  <a class="project_link" href="/our-work/project/{url_title}">
    <img src="/images/tmp-website-1.jpg" alt="replace" class="img-fluid" />
  </a>
  <div class="overlay">
    <div class="text">
      <h3>Project Title</h3>
      <p>Project Summary</p>
      <p class="view"><a href="/our-work/project/">VIEW</a></p>
    </div>
  </div>
  <!-- overlay -->
</div>
<!-- project -->

答案 1 :(得分:1)

为什么不拿走JavaScript并使用opacity设置它。我要做的就是将.overlay设置为opacity:0;并设置转换,以便叠加得很好,并在.project悬停时添加,overlay被赋予{{ 1}}

opacity:1;
.project { 
    position: relative;
    width: 95%;
    height: auto;
    padding: 0;
    overflow: hidden;
    
    }

.overlay { 
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background-color: #fff;
    opacity: 0;
    transition: all 0.2s ease-in;
 }

.project:hover .overlay { 
  opacity:0.9;
}

.text { width: 75%; height: 30%; margin: 50px auto; text-align: center; }

希望这有帮助。