我有一个简单的 React 应用程序,其中的 div 包含 SVG 球图像。 将鼠标悬停在图像上时,我希望它能够同时平滑地旋转和向左移动。 当悬停状态为 false 时,我希望它旋转并回滚到其初始位置。
我正在努力在 CSS 中结合这两种效果。
BallRoll.js
<div className="ball-holder">
<img
src={rollingBall}
loading="lazy"
width="223"
alt="rolling Ball"
className="ball"
/>
</div>
我对 CSS 有点迷失,无法找出组合所有内容的正确方法。 球.css
.ball {
display: block;
transition: 1s ease-in-out;
}
.ball:hover {
animation: animate2 5s linear;
}
@keyframes animate2 {
0%{
transform: rotate(0deg);
left:0;
}
50%{
transform: rotate(360deg);
left:calc(100% - 50px);
}
100%{
transform: rotate(0deg);
left:0;
}
它们并不完美,单独工作时效果很好,但在一起时就不行。有更好的建议和帮助吗?
这是一个工作示例。
需要注意的一点是,如果您仅对球的悬停应用影响,那么一旦球移动,悬停就会结束并返回到非悬停状态,从而导致快速闪烁。因此,当持球器悬停时,我会激活动画。
.ball {
width: 80px;
height: 80px;
border-radius: 50%;
background: linear-gradient(teal, #000);
}
.ball {
display: block;
transition: all 2s;
}
.ball-holder:hover .ball {
transform: translateX(calc(100vw - 80px)) rotate(360deg);
}
<div class="ball-holder">
<div class="ball"></div>
</div>
如果您创建两个单独的容器,则可以分别为它们设置动画
* {
box-sizing: border-box;
}
body {
margin: 0; padding:0;
font-family: system-ui, sans-serif;
color: black;
background-color: white;
}
#ball {
animation: roll 5s linear;
}
#ball-holder {
animation: moveLeft 5s linear;
}
@keyframes moveLeft {
0%{
transform: translateX(0px);
}
50%{
transform: translateX(300px);
}
100%{
transform: translateX(0px);
}
}
@keyframes roll {
0%{
transform: rotate(0deg);
}
50%{
transform: rotate(360deg);
}
100%{
transform: rotate(0deg);
}
}
<div id="ball-holder">
<img
id="ball"
src="https://media.istockphoto.com/photos/soccer-ball-isolated-3d-rendering-picture-id1257575611?k=20&m=1257575611&s=612x612&w=0&h=g530fFJspT42xFGY7HycLvpBKLXpJ2XAkKCRyY-SK80="
width="200"
alt="rolling Ball"
className="ball"
/>
</div>
* {
box-sizing: border-box;
}
body {
margin: 0; padding:0;
font-family: system-ui, sans-serif;
color: black;
background-color: white;
}
#ball {
animation: roll 5s linear;
}
#ball-holder {
animation: moveLeft 5s linear;
}
@keyframes moveLeft {
0%{
transform: translateX(0px);
}
50%{
transform: translateX(300px);
}
100%{
transform: translateX(0px);
}
}
<div id="ball-holder">
<img
id="ball"
src="https://media.istockphoto.com/photos/soccer-ball-isolated-3d-rendering-picture-id1257575611?k=20&m=1257575611&s=612x612&w=0&h=g530fFJspT42xFGY7HycLvpBKLXpJ2XAkKCRyY-SK80="
width="200"
alt="rolling Ball"
className="ball"
/>
</div>