CSS3 背景图动画

2,037 阅读1分钟

css代码

这种背景动画是通过移动背景图的位置实现的,这里没有使用CSS3的transition,而是用animation。

    @keyframes animatedBackground {
        from { background-position: 0 0; }
         to { background-position: 100% 0; }
    }

上面是动画定义,下面就要把它应用到一个具有背景图的页面元素上:

    #animate-area { 
      width: 560px; 
      height: 400px; 
      background-image: url(bg-clouds.png);
      background-position: 0px 0px;
      background-repeat: repeat-x;
    
      animation: animatedBackground 40s linear infinite;
    }

背景云图片以40秒一次的速度顺滑优雅的从左漂移到右,而且无缝的和下一次循环对接,这样无限循环漂浮下去。

不再需要js来操作动画是一件多么让人欣慰的事呀!虽然这些CSS写法上还有加一些浏览器引擎兼容前缀,看起来很讨厌,但至少比以前高效多了,而且易于配置。