歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 利用CSS3中animation屬性實現雪花飄落功能

利用CSS3中animation屬性實現雪花飄落功能

日期:2017/3/1 9:35:58   编辑:Linux編程

先介紹一下CSS3中的animation的特性吧。

在CSS3中我們可以使用animation屬性來創建復雜的動畫效果,包括移動,旋轉,縮放,傾斜(後幾個請參考css3中的transform,scale等屬性)等。而這一切,只需要我們創建關鍵幀(@keyframes),然後將自己想要實現的動作添加進去就可以實現。

利用CSS3中animation屬性實現雪花飄落功能演示網址:http://www.linuxidc.com/files/2014/12/sn/index.html

最終效果:

比如:

@keyframes bgchange{
from {background:red;}
to {background:yellow}
}

div:hover{
animation:bgchange 5s;
}

當鼠標懸停在<div>時,該<div>的背景顏色會在五秒之內從紅色變為黃色。

注意:使用animation和@keyframes時不同浏覽器需要加上不同的前綴名!

下面代碼實現雪花飄落功能:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<title>snowing snow</title>
<style>
body{
background: #eee;
}
@keyframes mysnow{
0%{
bottom:100%;
opacity:0;
}
50%{
opacity:1;
transform: rotate(1080deg);
}
100%{
transform: rotate(0deg);
opacity: 0;
bottom:0;
}
}
@-webkit-keyframes mysnow{
0%{
bottom:100%;
opacity:0;
}
50%{
opacity:1;
-webkit-transform: rotate(1080deg);
}
100%{
-webkit-transform: rotate(0deg);
opacity: 0;
bottom:0;
}
}
@-moz-keyframes mysnow{
0%{
bottom:100%;
opacity:0;
}
50%{
opacity:1;
-moz-transform: rotate(1080deg);
}
100%{
-moz-transform: rotate(0deg);
opacity: 0;
bottom:0;
}
}
@-ms-keyframes mysnow{
0%{
bottom:100%;
opacity:0;
}
50%{
opacity:1;
-ms-transform: rotate(1080deg);
}
100%{
-ms-transform: rotate(0deg);
opacity: 0;
bottom:0;
}
}
@-o-keyframes mysnow{
0%{
bottom:100%;
opacity:0;
}
50%{
opacity:1;
-o-transform: rotate(1080deg);
}
100%{
-o-transform: rotate(0deg);
opacity: 0;
bottom:0;
}
}
.roll{
position:absolute;
opacity:0;
animation: mysnow 5s ;
-webkit-animation: mysnow 5s ;
-moz-animation: mysnow 5s ;
-ms-animation: mysnow 5s ;
-o-animation: mysnow 5s ;
height:80px;
}
.div{
position:fixed;
}
</style>
</head>
<body>
<div id="snowzone" >
</div>
</body>
<script>
(function(){
function snow(left,height,src){
var div = document.createElement("div");
var img = document.createElement("img");
div.appendChild(img);
img.className = "roll";
img.src = src;
div.style.left=left+"px";
div.style.height=height+"px";
div.className="div";
document.getElementById("snowzone").appendChild(div);
setTimeout(function(){
document.getElementById("snowzone").removeChild(div);
// console.log(window.innerHeight);
},5000);
}
setInterval(function(){
var left = Math.random()*window.innerWidth;
var height = Math.random()*window.innerHeight;
var src = "s"+Math.floor(Math.random()*2+1)+".png";//兩張圖片分別為"s1.png"、"s2.png"
snow(left,height,src);
},500);
})();
</script>
</html>

兩張雪花圖片:

《HTML5與CSS3權威指南》及相配套源碼 http://www.linuxidc.com/Linux/2013-02/79950.htm

Copyright © Linux教程網 All Rights Reserved