CSS 转换和过渡

CSS Transform & transition

我有一张图片,我需要它的悬停不透明度为 0.5,然后它必须放大到 200%,并且当图片为全尺寸时将不透明度恢复到 1。

Example

我可以在悬停时进行缩放变换和不透明度,但是当图像为 200% 大小时,我需要缩放后的不透明度为 1。

#imagecontainer {
  border: 2px solid red;
  width: 251px;
  height: 251px;
  opacity: 1;
  position: absolute;
}
#image {
  width: 250px;
  height: 250px;
  border: 2px solid black;
  position: absolute;
  opacity: 1;
  -webkit-transition: -webkit-transform 1s ease-in-out;
}
#image:hover {
  opacity: 0.8;
  -webkit-transform: scale(2, 2);
}

由于有不止一个状态变化(即 opacity: 0.5 最初是在 transform 完成之前,然后是 opacity: 1 在转换完成之后,你不能用transition 单独因为转换只能更改 opacity 值一次并保留它。您需要使用 CSS3 动画或使用带有 transitionend 事件的 JS 更改样式。

下面是一个带有 CSS3 动画的示例片段,其中 hover 图像变为 opacity: 0.5 并且此状态一直保留到 99% 关键帧。所有这一切都发生在图像从没有任何变换到 transform: scale(2,2) 的过程中。然后在100%帧,transform保持原样,但opacity0.5变为1

#imagecontainer {
  border: 2px solid red;
  width: 251px;
  height: 251px;
  opacity: 1;
  position: absolute;
}
#image {
  width: 250px;
  height: 250px;
  border: 2px solid black;
  position: absolute;
  opacity: 1;
}
#image:hover {
  opacity: 0.5;
  animation: opacitynscale 1s ease-in-out forwards;
}
@keyframes opacitynscale {
  99% {
    transform: scale(2, 2);
    opacity: 0.5;
  }
  100% {
    transform: scale(2, 2);
    opacity: 1;
  }
<div id='imagecontainer'>
  <img id='image' src='http://lorempixel.com/250/250/nature/1' />
</div>


使用 CSS animation 而不是 transition 的缺点是,与 transition 不同,animation 不会自动产生相反的结果对悬停的影响(也就是说,它会快速回到原始状态,而不是逐渐返回)。还得写一个animation来实现反效果

如果您出于任何原因(包括上述原因)无法使用 CSS3 animation,那么您可以通过使用 transitionend 事件。

var img = document.getElementById('image'),
  mousein = false;

img.addEventListener('transitionend', function() { /* this event is fired when transition is over */
  if (mousein)
    img.style.opacity = 1; /* changes element's opacity to 1 */
  else
    img.style.opacity = null; /* remove inline style on hover out, otherwise it will override others */
});

/* to determine if mouse is over image or not */
img.addEventListener('mouseover', function() {
  mousein = true;
});
img.addEventListener('mouseout', function() {
  mousein = false;
});
#imagecontainer {
  border: 2px solid red;
  width: 251px;
  height: 251px;
  opacity: 1;
  position: absolute;
}
#image {
  width: 250px;
  height: 250px;
  border: 2px solid black;
  position: absolute;
  opacity: 1;
  transition: transform 1s ease-in-out;
}
#image:hover {
  opacity: 0.5;
  transform: scale(2, 2);
}
<div id='imagecontainer'>
  <img id='image' src='http://lorempixel.com/250/250/nature/1' />
</div>