利用JS给网页添加雪花飘落的效果

JavaScript05

利用JS给网页添加雪花飘落的效果,第1张

1、修改部分如下:

<html>

 <head>

  <script src="http://www.ren3.cn/Snow Demo/jsized.snow.min.js" type="text/javascript"></script>        

<script>

    /**

     * This function takes 2 arguments

     * First is the path to the directory with snowflake images

     * Second is the maximum number of snowflakes, please do not

     * set this number above 60 as it will impact the performance

     */

    createSnow("", 60)//目录改为当前目录

</script>

 </head>

 <body>

  测试

 </body>

</html>

2、在该网页目录 下 新添加 四张雪花图片 命名规则(snow0.gif snow1.gif snow2.gif snow3.gif)

/*

data:2022-11-17

author:lfp

move运动函数

dom--需要运动的对象

json--{width:100,height:100,left:100,top:100}

callback--回调函数 可调用自己 实现异步动画效果

*/

//主函数

function move(dom,json,callback){

//让每一次动画都是新的开始,防止出现动画一直不停的运行

if(dom.timer)clearInterval(dom.timer)

var i=0

var start=0

//在对象中增加timer 便于控制他停止

dom.timer=setInterval(function(){

i++

//循环每一个目标属性添加动画方法

for(var attr in json){

//获取当前attr的属性值 已经去除了px 还有 如果初始值是auto 用零代替

var cur=getStyle(dom,attr)

if(i==1)start=cur

//拿到该属性的目标值

var target=json[attr]

//设置分成10次增加增量 你可以根据需要修改

var speed=(target-start)/10

console.log(speed+"====="+cur)

//如果没有达到目标值就一直加

if(Math.abs(cur-target)>1){

dom.style[attr]=cur+speed+"px"

}else{

//达到目标值了就停止或者其他情况也停止

clearInterval(dom.timer)

//等停止了动画再回调函数进行另外的操作

if(callback)callback.call(dom)

}

}

},45)

}

//配套函数

function getStyle(dom,attr){

var value=""

if(window.getComputedStyle){

value=window.getComputedStyle(dom,false)[attr]

}else{

value=dom.currentStyle[attr]

}

value=parseInt(value)

return value || 0//如果你再样式中没有设置初始的值就会出现NaN 所以要用0来补充

}

function $(id){

//return document.getElementById(id)

return document.querySelector("#"+id)

}