WebAPI基础(六)
WebAPI基础(六)知识点
多次定时器
设置:setInterval( 回调函数, 时间间隔 )
清除:clearInterval( 定时器名称 )
特点:
每隔时间间隔,就执行一次函数体的内的代码。
永久性,
定时器常见问题:
-
动画定时器没办法停下来,检查设置定时器的时候有没有起名字
-
定时器会累加,如果用户快速点击按钮,鼠标快速移入移出都有可能出现该问题。
定时器做动画
-
让盒子动起来
-
动画函数封装
-
无缝轮播图 ( 预习 )
用定时器做动画
原理:定时器按照时间间隔,定时给盒子移动一下,盒子移动的代码写到定时器回调函数内反复执行。
定时器做动画实现步骤
-
设定一个定时器,并且起个名字
-
定时器内部让一个数据进行累加
-
把累加的数据赋值给 盒子样式
-
到达目标位置就停下来,清除定时器
参考代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>盒子动起来</title> <style> #box { width: 100px; height: 100px; background-color: pink; position: absolute; left: 100px; top: 100px; } </style> </head> <body> <div id="box">盒子</div> </body> </html> <script> /** * 定时器做动画: * 按照时间间隔给盒子移动一下,盒子移动的代码写到定时器回调函数内。 * * 1. 设定一个定时器,并且起个名字 * 2. 定时器内部让一个数据进行累加 * 3. 把累加的数据赋值给 盒子样式 * 4. 到达目标位置就停下来,清除定时器 * * */ var box = document.getElementById('box'); var num = 100; /* 1. 设定一个定时器,并给起个名字 */ var timer = setInterval(function () { /* 2. 让数据按照步长累加 */ num += 7; /* 3. 累加的数据赋值给盒子动起来 */ box.style.left = num + 'px'; /* 4. 分支判断,到达目标就停下来 */ if (num >= 500) { /* 4.1 清除定时器停下来 */ clearInterval(timer); /* 4.2 修正到达目标位置,防止超过目标位置 */ box.style.left = 500 + 'px'; } }, 24); </script>
定时器累加造成的影响
由于定时器做动画的效果经常要开放给用户触发,平时有锻炼手速的用户为了证明自己,一秒钟内点击了多次按钮,那你的定时器就要出问题了,定时器会累加。
动画函数封装
版本1
js部分:
/** * 动画函数 animate 版本1 * @param element 动画元素 * @param target 动画目标值 * @param step 动画步长(可选参数) */ function animate(element, target, step) { step = step || 10; var current = element.offsetLeft; clearInterval(element.timer); element.timer = setInterval(function () { current += current < target ? step : -step; element.style.left = current + 'px'; if (Math.abs(target - current) <= step) { clearInterval(element.timer); element.style.left = target + 'px'; } }, 24); }
HTML部分:
<style> #box { width: 1000px; height: 150px; background-color: #0a0; /* 给盒子定位 */ position: fixed; top: 100px; left: -1000px; } #closeBtn { width: 30px; height: 150px; background-color: skyblue; position: absolute; left: 1000px; cursor: pointer; text-align: center; } </style> </head> <body> <div id="box"> <div id="closeBtn">点击看历史版本</div> </div> <!-- 让元素发生位移的方式: 定位 做动画,一般都用定位 --> </body> </html> <script src="animate.js"></script> <script> /* * https://dnf.qq.com/main.shtml * */ var closeBtn = document.getElementById('closeBtn'); /**假设法: * 1. 立 flag * 2. 改 flag * 3. 用 flag * */ /* 1. 立 flag */ var flag = false; closeBtn.onclick = function () { /* 2. 改 flag */ flag = !flag; /* 3. 用 flag */ // if (flag) { // animate_V5(this.parentNode, 0, 100); // } else { // animate_V5(this.parentNode, -1000, 100); // } //三元表达式 flag ? animate(this.parentNode, 0, 100) : animate(this.parentNode, -1000, 100); } </script>