運行原理
通過定時器30毫秒執行一次滾動條上升,每次上升的高度為當前高度的80%,這樣就達到了上升緩沖的動畫效果。
判斷當滾動條高度超過一屏時,按鈕顯示,默認隱藏
知識要點
scrollTop//獲取滾動條高度 需要寫兼容clientHeight//可視窗口高度 需要寫兼容setInterval//定時器window.onscroll//滾動觸發事件
完整代碼
<!DOCTYPE html><html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>demo</title><style>body,h1,h2,h3,h4,h5,h6,hr,p,blockquote,dl,dt,dd,ul,ol,li,pre,form,fieldset,legend,button,input,textarea,th,td{margin:0;padding:0;}h1,h2,h3,h4,h5,h6{font-size:100%;}address,cite,dfn,em,var{font-style:normal;}code,kbd,pre,samp{font-family:courier new,courier,monospace;}ul,ol{list-style:none;}a{text-decoration:none;}a:hover{text-decoration:none;}sup{vertical-align:text-top;}sub{vertical-align:text-bottom;}legend{color:#000;}fieldset,img{border:0;}button,input,select,textarea{font-size:100%;}table{border-collapse:collapse;border-spacing:0;}.clear{clear: both;float: none;height: 0;overflow: hidden;}.bg{background:#9B1BC5; width: 1000px; height: 3000px; margin: 0 auto;}#gotop{width: 50px; height: 50px; background:#5490F5; color: #fff; position: fixed; left: 50%; bottom: 30px; text-align: center; font-family: "Microsoft Yahei",tahoma,arial; font-size: 14px; cursor: pointer; margin-left: 520px; display: none;}#gotop span{display: block;padding: 5px;}</style></head><body><div class="bg"></div><div id="gotop"><span>返回頂部</span></div><script type="text/javascript"> //在頁面加載完后立即執行多個函數方案 function addloadEvent(func){ var oldonload=window.onload; if(typeof window.onload !="function"){ window.onload=func; } else{ window.onload=function(){ if(oldonload){ oldonload(); } func(); } } } //在頁面加載完后立即執行多個函數方案結束 addloadEvent(b); function b(){ var gotop=document.getElementById("gotop"); var timer; var tf=true; //滾動觸發 window.onscroll=function(){ //獲取滾動條高度 var ostop=document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop; //獲取窗口可視區域高度 //console.log(ostop) var ch=document.documentElement.clientHeight||document.body.clientHeight; //如果頁面超過一屏高度按鈕顯示,否則隱藏 if(ostop>=ch){ gotop.style.display="block"; }else{ gotop.style.display="none"; } // if(!tf){ clearInterval(timer); } tf=false; } //點擊觸發 gotop.onclick=function(){ //創建定時器 timer=setInterval(function(){ //獲取滾動條高度 var ostop=document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop; //每次上升高度的20% var speed=Math.ceil(ostop/5); //每次上升當前高度的80%document.documentElement.scrollTop=document.body.scrollTop=ostop-speed; //如果高度為0,清除定時器 if(ostop==0){ clearInterval(timer); } tf=true; },30); } }</script></body></html>
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林網!
新聞熱點
疑難解答