我有一个图像,我需要它的悬停不透明度为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);
}
答案 0 :(得分:1)
由于有多个状态更改(即,opacity: 0.5
最初在transform
完成之前,然后opacity: 1
在转换完成之后,您无法使用{{ 1}}因为转换只能改变transition
值并保留它。你要么需要使用CSS3动画,要么使用带有opacity
事件的JS来改变样式。
下面是一个包含CSS3动画的示例代码段,其中transitionend
图片获取hover
,此状态将保留到opacity: 0.5
关键帧。所有这些都发生在图像从没有任何变换变为99%
时。然后在transform: scale(2,2)
框架,100%
保持不变,但transform
已从opacity
更改为0.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;
}
使用CSS <div id='imagecontainer'>
<img id='image' src='http://lorempixel.com/250/250/nature/1' />
</div>
代替animation
的缺点是,与transition
不同,transition
不会自动产生对鼠标悬停的反向影响(是的,它会恢复到原始状态而不会逐渐回归)。必须为反向效果编写另一个animation
。
如果由于某些原因(包括上述原因)无法使用CSS3 animation
,那么您可以使用animation
事件通过一些JavaScript来完成。
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);
}