CSS使用从左0到右0的绝对定位为div设置动画

Dan*_*ich 7 css css-animations

考虑这个样本.

http://jsfiddle.net/dfabulich/ncbzz5zu/3/

<html>
<body>
<style>
.container {
    position: relative;
    width: 80%;
    height: 100px;
    border: 1px solid black;
}

@keyframes slide {
  from { background-color: red; left: 0; }
  to { background-color: blue; right: 0; }
}

.animated {
    position: absolute;
    width: 20%;
    height: 100%;
    top: 0;
    background-color: red;
    animation-duration: 3s;
    animation-name: slide;
    animation-iteration-count: infinite;
}

</style>
<div class=container>
<div class=animated>
</div></div>
Run Code Online (Sandbox Code Playgroud)

预期:当颜色从红色变为蓝色时,红色矩形应从左到右平滑地动画.

实际:在Chrome/Firefox中,红色矩形慢慢地将颜色变为紫色,然后从左到右传送而不动画,然后从紫色慢慢变为蓝色.在Safari中,矩形出现在右侧,从不从那里移动,同时从红色到蓝色动画.

为什么会这样?我该如何解决?(我需要在CSS中修复它...没有JS,没有jQuery.)

Mic*_*ker 13

您需要为一个属性或另一个属性设置动画.您可以只为左侧设置动画并使用left: calc(100% - elemWidth)(elemWidth元素的宽度在哪里)或元素left: 100%; transform: translateX(-100%);的宽度是未知的.

还需要动画背景颜色.

.container {
	position: relative;
	width: 80%;
	height: 100px;
	border: 1px solid black;
}

.animated {
	position: absolute;
	width: 20%;
	height: 100%;
	top: 0;
	background-color: red;
	animation: 3s linear 0s slide infinite;
}

@keyframes slide {
  from { left: 0; }
  to {
    left: 100%;
    transform: translateX(-100%);
    background: blue;
  }
}
Run Code Online (Sandbox Code Playgroud)
<div class=container>
<div class=animated>
</div></div>
Run Code Online (Sandbox Code Playgroud)