CSS为div设置动画,绝对位置从左0到右0 [英] CSS animate a div with absolute positioning from left 0 to right 0

查看:418
本文介绍了CSS为div设置动画,绝对位置从左0到右0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例。

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>

预期:随着颜色从红色变为蓝色,红色矩形应从左向右平滑地动画。

Expected: The red rectangle should smoothly animate from left to right as the color changes from red to blue.

实际:在Chrome / Firefox中,红色矩形会逐渐将颜色更改为紫色,然后从左向右传送而不会设置动画,然后从紫色逐渐更改为蓝色。在Safari中,矩形会显示在右侧,并且永远不会从那里移动,而会从红色变为蓝色。

Actual: In Chrome/Firefox, the red rectangle slowly changes color to purple, then teleports from left to right without animating, and then slowly changes from purple to blue. In Safari, the rectangle appears on the right and never moves from there, while animating from red to blue.

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

Why is this happening? How can I fix it? (I need to fix it in CSS… no JS, no jQuery.)

推荐答案

您需要为一个属性或另一个属性设置动画。您可以左动画,也可以使用 left:calc(100%-elemWidth)(其中 elemWidth 是元素)或 left:100%; transform:transformX(-100%); 如果元素的宽度未知。

You need to animate one property or the other. You can just animate left and either use left: calc(100% - elemWidth) (where elemWidth is the width of the element) or left: 100%; transform: translateX(-100%); if the width of the element is unknown.

还需要设置背景颜色的动画。

Also need to animate background color.

.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;
  }
}

<div class=container>
<div class=animated>
</div></div>

这篇关于CSS为div设置动画,绝对位置从左0到右0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆