封装是面向对象的三个基本特征之一,将现实世界的事物抽象成计算机领域中的对象,对象同时具有属性和行为(方法),这种抽象就是封装.
如何封装: 将零散的的语句写进函数的花括号内,成为函数体,然后就可以调用了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box {
width: 200px;
height: 200px;
background: blue;
}
</style>
</head>
<body>
<button id="btn1">宽度到600px</button>
<button id="btn2">宽度到800px</button>
<div id="box"></div>
</body>
<script>
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
var box = document.getElementById("box");
var widthObj = 200;
/* var step = 2;
btn1.onclick = function () {
var timer1 = setInterval(function () {
if (widthObj < 600) {
widthObj += step;
box.style.width = widthObj + "px"
} else {
clearInterval(timer1)
}
}, 10)
}
btn2.onclick = function () {
var timer1 = setInterval(function () {
if (widthObj < 800) {
widthObj += step;
box.style.width = widthObj + "px"
} else {
clearInterval(timer1)
}
}, 10)
} */
// 封装的思想:
/*
可变化的量
1、最大宽度 widthMax
2、时间间隔 duration
3、每一步走的距离 step
*/
function changeWidth(widthMax, duration, step) {
var timer1 = setInterval(function () {
if (widthObj < widthMax) {
widthObj += step;
box.style.width = widthObj + "px"
} else {
clearInterval(timer1)
}
}, duration)
}
btn1.onclick = function () {
changeWidth(600, 10, 2);
}
btn2.onclick = function () {
changeWidth(800, 5, 1);
}
</script>
</html>