首页 > 解决方案 > Css Animations:尝试上下移动 div 元素并同时旋转其中的 img 元素失败

问题描述

项目描述:我正在寻求将两个动画应用于 div 内的嵌套图像,实际上Div有责任上下移动图像,因为图像被它迷住了,图像(​​img)嵌套在div,负责在 div 上下弹跳图像的同时连续旋转。

我想要什么

1.div内的图片要保持360度旋转

2.当1发生时,div 应该保持弹跳或上下移动

.ground {
	position: absolute;
	width: 100%;
	height: 20px;
	background-color: gray;
	top: 800px;
}
.ball-container {
	position: relative;
	width 100px;
	height: 100px;
	left: 50%;
	animation-name: bounce;
	animation-duration: 1s;
	animation-fill-mode: forwards;
	animation-direction: forwards;
	animation-timing-function: linear;
	animation-iteration-count: infinite;
}
@keyframes bounce{
	0% {
		top: 0px;
	}
	50% {
		top: 700px;
		width: 130px;
		height: 70px;
	}
	100% {
		top: 0px;
	}
}
img {
	position: absolute;
	width: 100px;
	height: 100px;
	animation-name: rotation;
	animation-direction: forwards;
	animation-duration: 1s;
	animation-timing-function: linear;
	animation-fill-mode: forwards;
    animation-iteration-count: infinite;
}
@keyframes rotation {
	from {transform: rotate(0deg);}
	to {transform: rotate(360deg);}
}
<html>
	<div class="ball-container" id="ball-container"><img src="https://image.flaticon.com/icons/svg/53/53283.svg" alt="ball" class="ball" id="ball"/>
	</div>
	<div class="ground"></div>
</html>

问题:弹跳过程很棒,但我不知道如何让图像在弹跳时旋转。

谢谢。

Codepen 链接


帖子已编辑,应用答案后没有问题

标签: htmlcssanimationcss-animations

解决方案


animation-iteration-count 在 img 旋转时应该是无限的,以匹配它反弹的次数,否则动画将运行一次并在盒子仍在弹跳时停止。另外你有一个错字,分号to {transform: rotate(360deg;)}应该在外面to {transform: rotate(360deg);}。这就是为什么它不起作用。

此外animation-direction:forwards是无效的,正确的值为animation-direction:normal

通过这些更正,代码为:

.ground {
	position: absolute;
	width: 100%;
	height: 20px;
	background-color: gray;
	top: 800px;
}
.ball-container {
	position: relative;
	width 100px;
	height: 100px;
	left: 50%;
	animation-name: bounce;
	animation-duration: 1s;
	animation-fill-mode: forwards;
	animation-direction: normal;
	animation-timing-function: linear;
	animation-iteration-count: infinite;
}
@keyframes bounce{
	0% {
		top: 0px;
	}
	50% {
		top: 700px;
		width: 130px;
		height: 70px;
	}
	100% {
		top: 0px;
	}
}
img {
	position: absolute;
	width: 100px;
	height: 100px;
	animation-name: rotation;
	animation-direction: normal;
	animation-duration: 1s;
	animation-timing-function: linear;
	animation-fill-mode: both;
    animation-iteration-count: infinite;
}
@keyframes rotation {
	from {transform: rotate(0deg);}
	to {transform: rotate(360deg);}
}
<html>
	<div class="ball-container" id="ball-container"><img src="https://image.flaticon.com/icons/svg/53/53283.svg" alt="ball" class="ball" id="ball"/>
	</div>
	<div class="ground"></div>
</html>


推荐阅读