每年年底,特别是在圣诞节,各大网站都玩起了“下雪”。在这弄一个,纪念:今年的结束,新年的开始。也祝福大家在新的一年里越来越好。
先看看效果(如果乱码或者不能查看 复制下面的代码保存在本地查看)
来看下代码,仅供参考
/** * LBS Snowing * Date: 2014-12-24 * ================================== **/ (function(exports) { function snow(opts) { opts = opts || {}; this.parent = opts.parent; //插入到哪里 this.speedY = opts.speedY || 5; //向下移动的速度 this.speedX = opts.speedX || 0; //左或者右移动的速度 this.name = opts.name || 'snow'; //用类名添加样式 this.html = opts.html || '❄'; //不要图片 用了特殊字符表示雪花 this.size = opts.size || '12'; //雪花大小 // this.color = opts.color || '#fff'; //雪花颜色 this.x = opts.x; //雪花的x坐标 对应 left this.y = opts.y; //雪花的y坐标 对应 top this.opacity = opts.opacity || 50; //雪花的透明度(0-100) this.div = null; //雪花在HTML文档中的引用对象 // 雪花移动 this.move = function() { this.div.style.top = this.div.offsetTop + this.speedY + 'px'; this.div.style.left = this.div.offsetLeft + this.speedX + 'px'; }; // 雪花初始化 this.init = function() { this.div = document.createElement('div'); this.div.style.fontSize = this.size + 'px'; // this.div.style.color = this.color; this.div.innerHTML = this.html; this.div.className = this.name; this.div.style.left = this.x + 'px'; this.div.style.top = this.y + 'px'; this.div.style.opacity = this.opacity / 100; this.div.style.filter = 'alpha(opacity=' + this.opacity + ')'; this.parent.appendChild(this.div); }; this.init(); } exports.Snowing = function(opts) { opts = opts || {}; this.parent = opts.parent || document.getElementsByTagName('body')[0]; this.count = 0; this.snows = []; this.timer = null; this.init(); }; Snowing.prototype = { init: function() { this.start(); }, create: function() { return new snow({ parent: this.parent, speedY: this.random(3, 10), speedX: this.random(-3, 3), size: this.random(20, 60), opacity: this.random(35, 90), x: this.random(0, this.width - 60), y: -60 }); }, createSnow: function() { if (this.count % 5 === 0) { this.snows.push(this.create()); } }, moveSnow: function() { if (this.snows.length < 1) return; for (var i = 0, len = this.snows.length; i < len; i++) { this.snows[i].move(); if (this.snows[i].div.offsetTop > this.height || this.snows[i].div.offsetLeft < -60 || this.snows[i].div.offsetLeft > this.width + 60) { this.parent.removeChild(this.snows[i].div); this.snows.splice(i, 1); len--; } } }, start: function() { var _this = this; this.css(); !function start() { _this.count++; _this.createSnow(); _this.moveSnow(); _this.timer = setTimeout(start, 17); }(); }, css: function() { var d = document, doc = d.documentElement, body = d.body; this.width = doc.clientWidth; this.height = doc.clientHeight; if (d.compatMode != "CSS1Compat") { this.width = body.clientWidth; this.height = body.clientHeight; } console.log(this.width +'////'+ this.height) }, random: function(min, max) { return (Math.random() * (max - min + 1) + min) >> 0; } }; }(window));