封装的时候,先实现其中的一个功能,之后叠加就可以了!
封装动画/函数库 |
---|
新建MyTool 文件夹,文件夹内新建一个MyTool.js 文件 |
举例:使用匿名函数定义$ 字面量 |
方式1:var myTool = { $:function (id) {return typeof id === "string" ? document.getElementById(id) : null; }}; |
调用:myTool.$(id); |
方式2:(function(w){w.myTool = {$:function (id) {return typeof id === "string" ? document.getElementById(id) : null; }};})(window); |
封装可以通过一个封闭作用域独立引用 |
1.轮播图|楼层效果
步长由大到小!
缓动公式:起始值 += (结束值 - 起始值) * 缓动系数 (0-1) 0.2
1)页面
<button id="btn">开始动画</button>
<div id="box"></div>
2)样式
<style>
#box {
background-color: deeppink;
width: 200px;
height: 200px;
margin-top: 10px;
}
</style>
3)JS函数
<script>
window.addEventListener('load', function (ev) {
//定义变量
var intervalID = null, begin = 0, target = 800;
//开始动画
myTool.$('btn').addEventListener('click', function (ev1) {
//清除定时器
clearInterval(intervalID);
//设置定时器
intervalID = setInterval(function () {
begin += (target - begin) * 0.2;
console.log(begin);
//判断,四舍五入
if(Math.round(begin) >= target){
begin = target;
clearInterval(intervalID);
}
//动画
myTool.$('box').style.marginLeft = begin + 'px';
}, 20);
})
})
</script>
引入:
<script src="MyTool/MyTool.js"></script>
var myTool = {
$:function (id) {return typeof id === "string" ? document.getElementById(id) : null; }
};