JS学习记录1

83 阅读1分钟
定时器的应用

分类:

  • (1)周期性定时器:每隔一段时间干什么事。setInterval(所做事情,间隔毫秒数),停止:clearInterval()
  • (2)一次性定时器:等待一定时间干什么事。setTimeout(所做事情,等待毫秒数),停止:clearTimeout() 练习: 设置一个弹窗广告,位于网页的右下方。只要用户点击关闭按钮马上关闭

实现思路:通过连续改变bottom值实现广告的向上向下移动。用了三个函数,一个moveUp用于广告往上滑,一个moveDown用于广告往下收,还有一个关闭close,用点击事件。 程序如下:

Document #adv{position:fixed;right:0;bottom:-560px;}
<div id="adv">
    <div>
        <button id="close">关闭</button>
    </div>
    <img src="adv.jpg">
</div>
<script>
    var timer=null;
    var adv=document.getElementById("adv")
    var close=document.getElementById("close")
    
    //向上走
    function moveup(){
        var cssStyle=document.defaultView.getComputedStyle(adv,null);
        var bottom=parseInt(cssStyle.bottom)
        if(bottom<0){
            bottom+=5
            adv.style.bottom=bottom+"px"
        }else{
            clearInterval(timer)
            timer=null
        }
    }
    //向下走
    function moveDown(){
        var cssStyle=document.defaultView.getComputedStyle(adv,null);
        var bottom=parseInt(cssStyle.bottom)
        if(bottom>-560){
            bottom-=5
            adv.style.bottom=bottom+"px"
        }else{
            clearInterval(timer)
            timer=null
        }
    }
    window.onload=function(){
        timer=setInterval(moveup,20)
    }
    //点击关闭按钮
    close.onclick=function(){
        clearInterval(timer)
        timer=null;
        timer=setInterval(moveDown,10)
    }
</script>
效果图:

Snipaste_2021-10-24_19-17-33.jpg 如有不对,欢迎指正。