我有一个图像网格。当单击一个时,应在顶部显示不透明性降低的覆盖,如果单击另一个,则前一个应恢复正常,而新的覆盖。我尝试了各种方式的加载,但没有任何效果:

<div class="grid-item">
  <a href="overlayActiveOne()">
    <img src="img/img.png" class="img-responsive">
  </a>
  <div id="overlay-one"></div>
</div>
<div class="grid-item">
  <a href="overlayActiveTwo()">
    <img src="img/img2.png" class="img-responsive">
  </a>
  <div id="overlay-two"></div>
</div>
<div class="grid-item">
  <a href="overlayActiveThree()">
    <img src="img/img3.png" class="img-responsive">
  </a>
  <div id="overlay-three"></div>
</div>
<div class="grid-item">
  <a href="overlayActiveFour()">
    <img src="img/img4.png" class="img-responsive">
  </a>
  <div id="overlay-four()"></div>
</div>


CSS:

#overlay-one #overlay-two #overlay-three #overlay-four {
    background-color: black;
    height: 100%;
    width: 100%;
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
}


JS:

function overlayActiveOne() {
    var overlay = document.getElementById("overlay-one")
    overlay.style.opacity = 0.7;
}

function overlayActiveTwo() {
    var overlay = document.getElementById("overlay-two");
    overlay.style.opacity = 0.7;
}

function overlayActiveThree() {
    var overlay = document.getElementById("overlay-three");
    overlay.style.opacity = 0.7;
}

function overlayActiveFour() {
    var overlay = document.getElementById("overlay-four");
    overlay.style.opacity = 0.7;
}

最佳答案

试试这个



$('.grid-item').click(function() {
  $(this).addClass('active');
  $('.grid-item').not(this).removeClass('active');
});

.grid-item {
  float: left;
  width: 33.3%;
  padding: 5px;
  box-sizing: border-box;
  transition: all 0.3s ease-in;
  position: relative;
  overflow: hidden;
}

.grid-item img{
  width: 100%;
}

.overlay {
  opacity: 0.7;
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  background: white;
  height: 100%;
  top: 0;
  left: 0;
  opacity: 0;
  transition: all 0.3s ease-in;
}

.grid-item.active .overlay{
  opacity: 0.7;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid-item">
  <img src="http://placehold.it/350x150">
  <div class="overlay">Overlay</div>
</div>

<div class="grid-item">
  <img src="http://placehold.it/350x150">
  <div class="overlay">Overlay</div>
</div>

<div class="grid-item">
  <img src="http://placehold.it/350x150">
  <div class="overlay">Overlay</div>
</div>

09-25 15:17