如何调整图像叠加大小相对于img大小

时间:2017-03-07 19:32:30

标签: javascript jquery html css image

我想在我的图像上设置叠加层,当我悬停图像时,图像上会出现一个叠加层,其大小与图像相同。当我调整窗口大小时,叠加层应自动调整大小。

我尝试过一些JS代码,但不起作用。它总是将宽度/高度设置为0px。

请告诉我如何解决这个问题。

var portImg = document.getElementById("portimg");
var overlay = document.getElementsByClassName("overlay");
var overlayh = overlay.style.height = portImg.clientHeight;
var overlayw = overlay.style.width = portImg.clientWidth;
/*
tried this 1 too

clientHeight + "px";
clientWidth + "px";
*/
.col-sm-6 {
  position: relative;
}

.img-container {
  width=100%
}

.img-container img {
  width=100%
}

.overlay {
  position: absolute;
  margin-top: 20px;
  text-align: center;
}

.overlay:hover {
  transform: rotate(0deg);
  opacity: .95;
}
<div class="col-sm-6">
  <div class="overlay">
  </div>
  <!-- overlay continer -->

  <div class="img-container">
    <img id="portimg" src="images/port.jpg" alt="">
  </div>
  <!-- img container -->
</div>
<!-- col -->

1 个答案:

答案 0 :(得分:1)

您可以使用自己的元素或伪元素单独使用CSS设置叠加层。在父级上使用absolute定位的覆盖图上使用relative定位,覆盖图将自动与父级进行缩放。

&#13;
&#13;
.img-container {
  position: relative;
}

.img-container img {
  display: block;
  width: 100%;
}

.overlay {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  text-align: center;
  opacity: 0;
  transition: opacity .25s;
  background: black;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1em;
}

.img-container:hover .overlay {
  opacity: .5;
}
&#13;
<div class="img-container">
  <img id="portimg" src="http://kenwheeler.github.io/slick/img/fonz1.png" alt="">
  <div class="overlay">overlay</div>
</div>
&#13;
&#13;
&#13;

如果您仍希望通过javascript控制叠加层的宽度和高度,我会创建一个与高度相匹配的函数,并在页面加载和window上调用它39; s resize事件。

&#13;
&#13;
.img-container {
  position: relative;
}

.img-container img {
  display: block;
  width: 100%;
}

.overlay {
  position: absolute;
  top: 0; left: 0; 
  /* right: 0; bottom: 0; */
  text-align: center;
  opacity: 0;
  transition: opacity .25s;
  background: black;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1em;
}

.img-container:hover .overlay {
  opacity: .5;
}
&#13;
<div class="img-container">
  <img id="portimg" src="http://kenwheeler.github.io/slick/img/fonz1.png" alt="">
  <div class="overlay" id="overlay">overlay</div>
</div>

<script>
  function matchHeight() {
  var img = document.getElementById('portimg'),
      overlay = document.getElementById('overlay');
  overlay.style.width = img.offsetWidth + 'px';
  overlay.style.height = img.offsetHeight + 'px';
}

window.addEventListener("load",function() {
  matchHeight();
});

window.addEventListener("resize", function() {
  matchHeight();
});
</script>
&#13;
&#13;
&#13;