首页 > 解决方案 > 在 :hover 和 @keyframes 中为同一个 div 使用变换属性

问题描述

div{
    width:100px;
    height: 100px;
    background-color: red;
    animation: anim 1s forwards;
    opacity: 0;
}
@keyframes anim{
    0%{transform: scale(1.2);opacity:0;}
    100%{transform: scale(1);opacity:1;}
}
div:hover{
    transform: scale(1.05);
}
<div></div>

我遇到了一些代码和转换属性的问题。

我在 div 上有一个入口动画。但是我的悬停动画不起作用,所以看起来它不起作用,因为我已经在动画中使用了“变换”。

有没有办法让它工作?

标签: csshtml

解决方案


transform您可以通过添加transitiondiv的变换来制作动画

/* property name | duration | timing function */
transition: transform 1s ease-in;

在你的情况下

@keyframes anim{
  0%{transform: scale(1.2);opacity:0;}
  100%{transform: scale(1);opacity:1;}
}
div:hover{
    transform: scale(1.05);
}
div{
    width:100px;
    height: 100px;
    background-color: red;
    animation: anim 1s;
    transition: transform 1s;
}
<div>Hello</div>

演示

过渡 - MDN - DOC


推荐阅读