将图像悬停在另一个图像上

时间:2017-03-13 19:14:16

标签: css hover fading

我对soemthing很困惑很可能很简单,但我无法弄明白。当我将鼠标悬停在图像1上时,我希望图像2覆盖图像1。 因此,目标是将图像1与包含半透明颜色渐变的图像2重叠。我知道这可以用纯CSS实现,但我需要这样。

以下CSS代码来自另一个Typo3 CMS网站,并在那里运作。

但是,我似乎无法使其在Typo3网站的其他部分/元素上工作,我甚至无法在像这样的简单基本HTML页面上工作。

<!DOCTYPE html>
<html>
<body>

<style>

.container {
    height: 300px;
    width: 500px;
    position: relative;
    background-color: red;
}

img {
    position: relative;
    height: 100%;
    width: 100%;
}

.container .hover-second-image-over-first-image:hover {
  width:100%;
  height:100%;
  background-image:url(image_02.jpg);
  background-position:top left;
  background-repeat: no-repeat;
  background-size:100%;
  position:absolute;
  opacity:0;
  -webkit-transition: all 0.4s ease;
  -moz-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}
</style>

<div class="container">
 <div class="hover-second-image-over-first-image"></div>
 <img src="image_01.jpg" />
</div>


</body>
</html>

编辑:

好的,所以“z-index:10;”确实为我修好了。这段代码适用于:

.container {
    height: 300px;
    width: 500px;
    position: relative;
    background-color: red;
}

img {
    position: relative;
    height: 100%;
    width: 100%;
}

.container .hover-second-image-over-first-image {
  width:100%;
  height:100%;
  background-image:url(image_02.jpg);
  background-position:top left;
  background-repeat: no-repeat;
  background-size:100%;
  position:absolute;
  z-index:10;
  opacity:0;
  -webkit-transition: all 0.4s ease;
  -moz-transition: all 0.4s ease;
  -o-transition: all 0.4s ease;
  transition: all 0.4s ease;
}

.container:hover .hover-second-image-over-first-image {
  opacity:.3;
}

但我仍然想知道为什么代码之前在其他网站上没有任何z-index位置......

1 个答案:

答案 0 :(得分:1)

要注意的一些事情:

  • 请勿将您的样式放在<body>标记

  • 尝试使用:hover状态设置要在图像上查看的图层,不要使用.container .hover-second-image-over-first-image状态,因此必须为:hover

  • 对所有.container元素

  • 使用.container { height: 300px; width: 500px; position: relative; background-color: red; } img { position: relative; height: 100%; width: 100%; } .container .hover-second-image-over-first-image { width: 100%; height: 100%; background:blue; opacity:0; position: absolute; top:0; left:0; z-index:10; -webkit-transition: all 0.4s ease; -moz-transition: all 0.4s ease; -o-transition: all 0.4s ease; transition: all 0.4s ease; } .container:hover .hover-second-image-over-first-image { opacity:.7; }操作

<div class="container">
  <div class="hover-second-image-over-first-image"></div>
  <img src="http://placehold.it/200" />
</div>
var red = document.getElementById('red')
var back = document.getElementById('back')
red.addEventListener('click', function() {
    this.classList.add('hidden')
})
back.addEventListener('click', function() {
    red.classList.remove('hidden')
})