CSS背景位置从右到左动画

我正在尝试为背景图像设置动画,以便图像从右到左显示。 我使用的图像宽度大于背景所在的div容器的宽度。 一开始,背景如下

background: url(../img/zeppelin.png); background-repeat: no-repeat; background-position: right; 

但是当页面加载时,我想要对背景进行动画处理,使其位于左侧。 这应该采取例如。 2秒,只应该做一次。 (图像应该在之后左侧定位)。

我不想使用任何鼠标事件或伪类。 有没有办法通过只使用CSS来动画它? 我尝试使用关键帧找到解决方案但没有成功。

您可以尝试使用this tutorialCSS背景动画

 @keyframes animatedBackground { 0% { background-position: 0 0; } 100% { background-position: -300px 0; } } @-moz-keyframes animatedBackground { 0% { background-position: 0 0; } 100% { background-position: -300px 0; } } @-webkit-keyframes animatedBackground { 0% { background-position: 0 0; } 100% { background-position: -300px 0; } } @-ms-keyframes animatedBackground { 0% { background-position: 0 0; } 100% { background-position: -300px 0; } } @-o-keyframes animatedBackground { 0% { background-position: 0 0; } 100% { background-position: -300px 0; } } html { width: 100%; height: 100%; background-image: url(background.png); background-position: 0px 0px; animation: animatedBackground 10s linear infinite; -moz-animation: animatedBackground 10s linear infinite; -webkit-animation: animatedBackground 10s linear infinite; -ms-animation: animatedBackground 10s linear infinite; -o-animation: animatedBackground 10s linear infinite; } 

示例 : http : //jsfiddle.net/verber/6rAGT/5/

希望你需要的东西)

工作链接: http : //sagiavinash.com/labs/tests/css_anim/

这是一个非正统的伎俩。

      

style.css中:

 img{ background-position:right; 

这里发生的是最初提交的

提到的css。 之后因为外部样式表就在之前的 。 因此,在加载资源之后加载style.css。 所以css的实现存在滞后,这使我们可以应用css转换。

没有JAVASCRIPT,没有事件我们仍然得到我们想要的!

你需要使用动画和数字作为值,因此它可以计算开始 – 结束之间的每个位置。 基本上它将是:

 html { background:url(http://gravatar.com/avatar/21ffdef6c07de75379e31a0da98d9543?s=512) no-repeat; background-size:10%;/* demo purpose */ background-position: 100% 0; animation: bgmve 2s; } @keyframes bgmve { to {background-position: 0 0;} /* make it short */ } 

DEMO


要在加载时触发动画,您可以通过javascript将类添加到html:

  onload=function() { var root = document.getElementsByTagName( 'html' )[0]; // '0' to assign the first (and only `HTML` tag) root.setAttribute( "class", "move" ); } 

和css变成:

 html { background:url(http://gravatar.com/avatar/21ffdef6c07de75379e31a0da98d9543?s=512) no-repeat; background-size:10%; background-position: 100% 0; } .move { animation: bgmve 2s; } @keyframes bgmve { to {background-position: 0 0; } } 

你已经标记了Jquery。 所以将为您提供Jqueryfunction。

 $( "#ID" ).animate({ left: "50px", }, 2000); 

上课:

  $( ".class" ).animate({ left: "50px", }, 2000); 

您可以更改“左”acc的值。 到你想要的位置。

设定position:relative; left:50%; 例如,在document.ready事件中,使用jquery animate将左值减小为例如0。

看看这个小提琴