马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
1.一次性定时器:先等待一段时间,再自动执行一次任务,自动停止
如何使用:3步:和周期性完全一样:
1. 任务函数的结尾:何种情况下重新启动等待
2. 只要停,就要定义全局变量timer
3. 启动:timer=setTimeout(taskFun,等待时间);
4. 停止:clearTimeout(timer);
timer=null;
何时需要留住this:对象的方法内又启动了定时器的回调
方法中定义var self=this,留住this
回调函数中:self.方法名();
例如:模拟页面右下角广告弹出框
- <!DOCTYPE html>
- <html>
- <head>
- <title>窗口右下角消息弹出框</title>
- <meta charset="utf-8"/>
- <style>
- *{margin:0;padding:0}
- #msg{width:200px;height:200px;
- position:fixed;
- right:30px;
- bottom:-200px;
- background-color:LightBlue;
- }
- #msg>a{float:right;
- padding:5px 10px;
- border:1px solid black;
- cursor:pointer;
- }
- </style>
-
- </head>
- <body>
- <div id="msg">
- <a>X</a>
- </div>
- <script>
- var adv={
- duration:1000,//总时长3秒
- interval:30, //每步间隔50毫秒
- div:null, //保存移动的div对象
- height:0, //div的总高度
- init:function(){
- //找到div对象,保存在div中
- this.div=document.getElementById("msg");
- /*获得div对象高度,保存在height中*/
- var style=getComputedStyle(this.div);
- //获得div对象最终应用的所有样式属性
- this.height=parseFloat(style.height);
- },
- moveUpStep:function(){//向上移动一步
- var self=this;//用局部变量self转接this指的当前对象
- //获得div现在最终应用的bottom值
- var style=getComputedStyle(self.div);
- var bottom=parseFloat(style.bottom);
- //将bottom值+=height*interval/duration;
- bottom+=self.height*self.interval/self.duration;
- //将bottom的值设置回div的内联样式中,替代外部样式
- self.div.style.bottom=bottom+"px";
- //如果bottom值<=0,就再次注册一次性定时器
- if(bottom<=0){//必须使用adv对象调用moveUpStep
- setTimeout(function(){self.moveUpStep()},self.interval);
- }
- },
- startMoveUp:function(){//让div开始向上移动
- var self=this;
- //注册一次性定时器,放入moveUpStep
- setTimeout(function(){self.moveUpStep()},self.interval);
- },
- moveDownStep:function(){//向下移动一步
- var self=this;
- //获得div现在最终应用的bottom值
- var style=getComputedStyle(self.div);
- var bottom=parseFloat(style.bottom);
- //将bottom值-=height*interval/duration;
- bottom-=self.height*self.interval/self.duration;
- //将bottom的值设置回div的内联样式中,替代外部样式
- self.div.style.bottom=bottom+"px";
- //如果bottom值>=-height,
- if(bottom>=-self.height){
- // 就再次注册一次性定时器
- setTimeout(function(){
- self.moveDownStep();
- },self.interval);
- }else{//否则
- // 在注册一次startMoveUp,设置间隔为5000毫秒
- setTimeout(function(){
- self.moveUpStep();
- },5000);
- }
- },
- startMoveDown:function(){
- var self=this;
- //注册一次性定时器
- setTimeout(function(){
- self.moveDownStep();
- },self.interval);
- }
- }
- window.onload=function(){
- adv.init();
- adv.startMoveUp();
- document.querySelector("#msg>a").onclick=function(){
- adv.startMoveDown();
- }
- }
- </script>
- </body>
- </html>
复制代码下面是页面效果:
点击右上角的 X 后,广告框会慢慢退回去,3秒后广告框又会弹出,如此反复循环。
|