CSS转换和过渡

技工

我有一个图像,我需要将其悬停不透明度设置为0.5,然后它必须按比例缩放到200%,并且在图像按比例缩放时必须将不透明度提高到1。

例子

在此处输入图片说明

我能够在悬停时进行缩放变换和不透明度,但是当图像为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,要么必须使用CSS3动画或使用带有transitionend事件的JS更改样式

Below is a sample snippet with CSS3 animations where on hover the image gets opacity: 0.5 and this state is retained till the 99% keyframe. All this happens while the image goes from not having any transform to transform: scale(2,2). Then at the 100% frame, the transform is retained as it is but opacity is changed from 0.5 to 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>


The downside of using CSS animation instead of transition for this is that unlike transition, the animation wouldn't automatically produce the reverse effect on hover out (that is, it would snap back to original state and not gradually go back). Another animation must be written for the reverse effect.

如果animation出于某种原因(包括上述原因)无法使用CSS3 ,则可以通过使用该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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章