- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title>131-140章总结</title>
- </head>
- <body>
- <pre>
- 131. 定时器的应用1
- </pre>
- <style type="text/css">
- #box1 {
- width: 100px;
- height: 100px;
- background-color: red;
- position: absolute;
- left: 0;
- }
- </style>
- <button id="btn01">点击按钮以后box1向右移动</button>
- <div class="" style="position: relative;height: 200px;">
- <div id="box1"></div>
- </div>
- <script type="text/javascript">
- console.log("第131");
- var box1 = document.getElementById("box1");
- var btn01 = document.getElementById("btn01");
- var timer1;
- btn01.onclick = function(){
- clearInterval(timer1);
- timer1 = setInterval(function(){
- var oldValue = parseInt(getStyle(box1,"left"));
- var newValue = oldValue + 10;
- if(newValue > 800){
- newValue = 800;
- }
- box1.style.left = newValue + "px";
- if(newValue == 800){
- clearInterval(timer1);
- }
- },30);
- };
- /*
- * 定义一个函数,用来获取指定元素的当前的样式
- * 参数:
- * obj 要获取样式的元素
- * name 要获取的样式名
- */
- function getStyle(obj , name) {
- if(window.getComputedStyle){
- //正常浏览器的方式,具有 getComputedStyle()方法
- return getComputedStyle(obj , null)[name];
- } else {
- //IE8的方式,没有getComputedStyle()方法
- return obj.currentStyle[name];
- }
- }
- </script>
- <pre>
- 132. 定时器的应用2
- </pre>
- <div class="" style="position: relative;height: 200px;">
- <button id="btn21">点击按钮以后box1向右移动</button>
- <button id="btn22">点击按钮以后box1向左移动</button>
- <br /><br />
- <div id="box21" style="width: 100px;height: 100px;background-color: #ddd;position: absolute;"></div>
- </div>
- <script type="text/javascript">
- console.log("第132");
- var box21 = document.getElementById("box21");
- var btn21 = document.getElementById("btn21");
- var btn22 = document.getElementById("btn22");
- //点击按钮以后,使box1向右移动(left值增大)
- btn21.onclick = function(){
- move(box21 , 800 , 10);
- };
- //点击按钮以后,使box1向左移动(left值减小)
- btn22.onclick = function(){
- move(box21 , 0 , 10);
- };
- //定义一个变量,用来保存定时器的标识
- var timer2;
- //尝试创建一个可以执行简单动画的函数
- /*
- * 参数:
- * obj:要执行动画的对象
- * target:执行动画的目标位置
- * speed:移动的速度(正数向右移动,负数向左移动)
- */
- function move(obj , target ,speed){
- // 关闭上一个定时器
- clearInterval(timer2);
- // 获取元素目前的位置
- var current = parseInt(getStyle(obj,"left"));
- //判断速度的正负值
- //如果从0 向 800移动,则speed为正
- //如果从800向0移动,则speed为负
- if(current > target){
- //此时速度应为负值
- speed = -speed;
- }
- //开启一个定时器,用来执行动画效果
- timer2 = setInterval(function(){
- //获取obj的原来的left值
- var oldValue = parseInt(getStyle(obj,"left"));
- //在旧值的基础上增加
- var newValue = oldValue + speed;
- //判断newValue是否大于800
- //从800 向 0移动
- //向左移动时,需要判断newValue是否小于target
- //向右移动时,需要判断newValue是否大于target
- if((speed < 0 && newValue < target) || (speed > 0 && newValue &