Javascript下雪特效
本文来自lyz810的空间,http://hi.baidu.com/lyz810/item/1f4567768dfbd23d71442399效果演示:http://www.lyz810.tk/lab/Snow.php
该特效适用于非IE浏览器,由于下雪由setTimeout调用,IE在setTimeout的误差过大
调用方式:lyz.snow(option)
option为json格式:
stopdiv:雪花停留元素,可选项,可以是一个HTMLElement或String,当参数为String类型时,为指定的id作为停留元素
speed:默认速度为每50ms执行一次,该参数可选项,数值类型,有效范围0~4,数值越大,速度越快,但对浏览器性能要求会越高,适当做测试,选择一个恰当的速度
num:默认雪花数100,该参数可选项,数值类型,建议不要超过200,否则大多数浏览器对CPU的开销极大,一般设置50左右即可 sym:默认为*,雪花默认样式,通常不需要更改
var lyz=lyz||{};
lyz.snow=function(option){
option=option||{};
var G=function(id){
return document.getElementById(id);
}
var g=function(id){
if(typeof id=='string'){
return G(id);
}else if(typeof id=='object'){
return id;
}
}
var snowspeed=;
var snowflakes = option.sym||'*';//闆姳鏍峰紡
var drops = option.num||100;//闆姳鏁扮洰
var stopdiv = option.stopdiv||null;
var speed = snowspeed||50;
var snowflake = new Array();
var x = new Array();
var y = new Array();
var mv = new Array();
var maxx = document.documentElement.clientWidth;
var maxy = document.documentElement.clientHeight;
for(i = 0; i < drops; i++){
document.write('<div id="lyz_snow'+i+'" style="position:absolute;color:white;cursor:default">'+snowflakes+'</div>');
snowflake = G('lyz_snow'+i)
x = Math.random()*maxx-40;
y = -Math.random()*maxy;
snowflake.style.left = x+'px';
snowflake.style.top = y+'px';
mv = (Math.random()*5)+0.5;
snowflake.style.fontSize = ((Math.random()-0.5)*10)+16;
}
var startsnow=function(){
var stopsnow = true;
for(i=0; i<drops; i++){
var movex = (Math.random()-0.75)*2.5;
if(stopdiv){
if(x<g(stopdiv).offsetLeft||x>g(stopdiv).offsetLeft+g(stopdiv).offsetWidth||y<g(stopdiv).offsetTop-15-window.scrollY||y>g(stopdiv).offsetTop+g(stopdiv).offsetHeight-15-window.scrollY){
x+=movex;
y+=mv;
stopsnow = false;
}
}else{
x+=movex;
y+=mv;
stopsnow = false;
}//endOfElse
if(x < 0||x>maxx){
x = Math.random()*maxx-40;
y = 10;
}
if(y > maxy-40){
y = 10;
}
snowflake.style.left = x+'px';
snowflake.style.top = y+document.body.scrollTop+'px';
}//endOfFor
if(!stopsnow){
setTimeout(startsnow,speed);
}
}//endOfStartSnow
startsnow();
}
页:
[1]