【问题标题】:CSS Transform & transitionCSS 变换和过渡
【发布时间】:2015-11-29 13:39:25
【问题描述】:

我有一个图像,我需要它的悬停不透明度为 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);
}

【问题讨论】:

  • 你有不止一个状态变化,所以你应该动画而不是过渡(或者使用一些JS和CSS)。

标签: css formatting css-transitions css-animations


【解决方案1】:

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

下面是一个带有 CSS3 动画的示例 sn-p,其中在 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 事件使用一点 JavaScript 来完成。

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>

【讨论】:

    猜你喜欢
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 2021-02-14
    相关资源
    最近更新 更多