×

【每日一学】滚动到顶端代码

作者:Terry2017.01.03来源:Web前端之家浏览:11016评论:0
关键词:滚动

今天来学习下“滚动带顶端代码”直接贴出来咯。

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>不能预览,请直接辅助在浏览器运行</title>
<style>
#div1 {width: 100px; height: 100px; background: red; position: absolute; right: 0; top: 0;}
</style>
<script>
window.onload = function() {
    var oDiv = document.getElementById('div1');
    var iTimer = null;
    var b = 0;
    setTop();
    window.onscroll = function() {
        console.log(2);
        if (b != 1) {//如果b=1那么,当前的scroll事件是被定时器所触发,如果不等于1,那么就是非定时器的其他任何一个操作触发该事件
            clearInterval(iTimer);
        }
        b = 2;
        setTop();
    }
     oDiv.onclick = function() {
        clearInterval(iTimer);
        var iCur = iSpeed = 0;
        iTimer = setInterval(function() {
            iCur = document.documentElement.scrollTop || document.body.scrollTop;
            iSpeed = Math.floor( ( 0 - iCur ) / 8 );
            if ( iCur == 0 ) {
                clearInterval(iTimer);
            } else {
                document.documentElement.scrollTop = document.body.scrollTop = iCur + iSpeed;
            }
            console.log(1);
            b = 1;
          }, 30);
      }
  function setTop(){
        var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
        oDiv.style.top=scrollTop+document.documentElement.clientHeight-oDiv.offsetHeight+'px';
    }
}
</script>
</head>
<body style="height: 2000px;">
    <div id="div1"></div>
</body>
</html>

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/biji11.html

网友评论文明上网理性发言 已有0人参与

发表评论: