js封裝-簡單雪花插件
今天學習了JS的封裝,重點是學習函數的作用域,對暴露的接口進行操作。在老師講的基礎上增加了雪花顏色的隨機值,並同時判斷雪花下落的邊界,解決滾動條抖動的問題。
效果圖
代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>show</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
background: #000;
}
</style>
</head>
<body>
<script src="js/snow.js"></script>
<script>
fn.snow({
minSize: 5,
maxSize: 30,
newOn: 100,
flakeSpeed: 5
});
</script>
</body>
</html>
snow.js
!function () {
// body...
window.fn = {};
fn.snow = function(options) {
console.log('qq')
var defaults = {
minSize: 5,
maxSize: 20,
newOn: 200,
flakeSpeed: 10
}
var option = options || defaults;
var hash = ['A', 'B', 'C', 'D', 'E', 'F'];
var documentWidth = document.documentElement.clientWidth;
var documentHeight = document.documentElement.clientHeight;
console.log('kkk');
var interval = setInterval(function(){
var flake = document.createElement("div");
var flakeSize = option.minSize + Math.random() * (option.maxSize - option.minSize);
var flakeX = Math.random() * documentWidth - flakeSize;
// var flakeY = Math.random() * documentHeight;
var opacity = Math.random() + 0.2;
var flakeColor = getColor();
flake.style.cssText = "border-radius:50%;position:absolute;box-shadow:5px 5px 5px rgba(20, 20, 20, 0.5);height:" + flakeSize + "px;width:"
+ flakeSize + "px;background:" + flakeColor + ";opacity" + opacity + ";left:" + flakeX + "px;";
document.body.appendChild(flake);
animate(flake, option.flakeSpeed, flakeSize);
}, option.newOn);
function animate(obj, speed, flakeSize) {
var top = 0;
var timer = setInterval(function() {
top += speed;
if (top + flakeSize > documentHeight) {
clearInterval(timer);
obj.parentNode.removeChild(obj);
}
obj.style.top = top + "px";
},13);
}
function getColor() {
var color = '#';
for (var i = 0; i < 6; i++) {
var tmp = Math.floor(Math.random() * 16 + 1);
if (tmp > 9) {
tmp = hash[tmp - 10];
}
color += tmp;
}
// console.log(color);
return color;
}
}
}();
感想
通過JS封裝的練習,讓我對函數作用域有了更清晰的認識,同時對於Math
對象也有了更熟練的掌握,同時讓我認識到細節決定成敗,不管是學前端還是搞ACM
都要有嚴謹的思維。