在:: before伪元素上使用CSS转换

Tig*_*yan 4 transactions css3 pseudo-element css-transitions

.posts .img-hover:before {
  content: '';
  display: block;
  opacity: 0;
  -webkit-transition: opacity 1.2s ease;
  -moz-transition: opacity 1.2s ease;
  -ms-transition: opacity 1.2s ease;
  -o-transition: opacity 1.2s ease;
  transition: opacity 1.2s ease-out;
}
.posts .img-hover:hover:before {
  content: '';
  display: block;
  background: url("img/Texture1.png");
  width: 320px;
  /* image width */
  height: 220px;
  /* image height */
  position: absolute;
  top: 13px;
  right: 2px;
  opacity: 1;
}
Run Code Online (Sandbox Code Playgroud)
<div class="posts">
  <a href="#">
    <h2 class="postname"> 
         Travel Flashback #1 </h2>
  </a>
  <a class="img-hover" href="#">
    <img width="960" height="720" src="http://.." class="img-hover" alt="" />
  </a>
</div>
Run Code Online (Sandbox Code Playgroud)

我有这个代码的一个问题.如你所见,我希望转换到伪元素::之前,它有bkg img.

当我悬停时,过渡工作顺利,但是当我离开鼠标时,bkg img会立即消失而不会过渡.

你能建议一下吗?

小智 6

在悬停时,您可能只希望与转换相关的css,而不是伪元素的实际样式.试试这个

.posts .img-hover:before {
    content: '';
    display: block;
    background: url("img/Texture1.png");
    width: 320px; /* image width */
    height: 220px; /* image height */
    position: absolute;
    top: 13px;
    right: 2px;
    opacity: 0;
    -webkit-transition: opacity 1.2s ease;
    -moz-transition: opacity 1.2s ease;
    -ms-transition: opacity 1.2s ease;
    -o-transition: opacity 1.2s ease;
    transition:  opacity 1.2s ease-out;
}
.posts .img-hover:hover:before{
    opacity: 1;
}
Run Code Online (Sandbox Code Playgroud)

  • 我有完全相反的问题(即“opacity: 1”突然出现在“after”伪元素上,但根据“transition”淡出),尽管应用了计时函数和延迟。知道为什么吗? (2认同)