1 <!DOCTYPE html>
2 <html>
3 <head lang="en">
4 <meta charset="UTF-8">
5 <title></title>
6 <link rel="stylesheet" href="css/ad.css"/>
7 </head>
8 <body>
9 <div id="adver">
10 <a href="javascript:adv.moveDown()">×</a>
11 </div>
12 <script>
13 var adv={
14 DISTANCE:0, //弹出的距离
15 DURATION:2000, //
16 STEPS:400,
17 interval:0,
18 step:0,
19 adv:null, //对象
20 WAIT:3000,
21 moved:0, //已经移动的步数
22 init:function(){
23 //获取广告区域对象id为adver的div
24 this.adv=document.getElementById('adver');
25 //获取adv计算后的height,保存在DISANCE属性中
26 this.DISTANCE=parseFloat(
27 getComputedStyle(this.adv).height
28 );
29 //计算interval=DURATION/STEPS
30 this.interval=this.DURATION/this.STEPS;
31 //计算step=DISTANCE/STEPS
32 this.step=this.DISTANCE/this.STEPS;
33 debugger;
34 this.move(1);//调用this.moveUp()启动上移
35 },
36 move:function(dir,callback){//启动上移
37 //启动周期性定时器,传入任务函数moveUpStep,设置时间间隔为interval, 将序号保存在timer属性中
38 this.timer=setInterval(
39 this.moveStep.bind(this,dir,callback),
40 this.interval
41 );
42 },
43 moveStep:function(dir,callback){//上移一步
44 //获得adv计算后的bottom
45 var bottom=parseFloat(
46 getComputedStyle(this.adv).bottom
47 );
48 //设置adv的bottom为bottom+this.step
49 this.adv.style.bottom=
50 bottom+dir*this.step+"px";
51 this.moved++;
52 //如果moved等于STEPS
53 if(this.moved==this.STEPS){//动画结束
54 //停止定时器,清空timer, moved归0
55 clearInterval(this.timer);
56 this.timer=null;
57 this.moved=0;
58 if(callback){
59 callback();
60 }
61 }
62 },
63 moveDown:function(){
64 //如果?
65 if(this.timer==null){//防动画叠加!
66 this.move(-1,function(){
67 //启动一次性定时器: 传入任务函数move,提前绑定this和1, 设置等待时间为WAIT
68 setTimeout(
69 this.move.bind(this,1),this.WAIT //这里是判断回调函数的依据
70 );
71 }.bind(this)); //这里绑定一定要 绑定回callback
72 }
73 }
74 }
75 adv.init();//this->adv
76 </script>
77 </body>
78 </html>
#adver{
width: 200px;
height:200px;
position: fixed;
bottom:-200px;
right: 0px;
background: #f0f0f0;
}
#adver>a{
float: right;
}