CSS3如何实现雪花飘落特效

寻技术 Html/CSS 2023年07月23日 59

这篇文章主要介绍“CSS3如何实现雪花飘落特效”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“CSS3如何实现雪花飘落特效”文章能帮助大家解决问题。

在CSS3中我们可以使用animation属性来创建复杂的动画效果,包括移动,旋转,缩放,倾斜(后几个请参考css3中的transform,scale等属性)等。而这一切,只需要我们创建关键帧(@keyframes),然后将自己想要实现的动作添加进去就可以实现。
比如:

@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>
关闭

用微信“扫一扫”