原生js、實現緩慢回到頂部效果

原生js、實現緩慢回到頂部效果

1.Demo展示:

Alt

2 . Html佈局:

	<!--返回頂部-->
	<div class="gotop">
		<img src="images/top/toTop.jpg">
	</div>

3. css樣式表:

/*回到頂部*/
	.gotop{
		width:70px;
		height:70px;
		position:fixed;
		top:70%;
		right:50%;
		margin-right:-725px;
		display:none;
		cursor:pointer;
	}
	
	.gotop img{
		width:100%;
		height:100%;
	}

4. 原生js代碼:

window.onload = function(){
		var divs = document.querySelector(".gotop");
		//獲取可視區域的高度;
		var clientH = document.documentElement.clientHeight;
		var timer = null;
		var Ontop = document.documentElement.scrollTop || document.body.scrollTop;//兼容性設置;	

		window.onscroll = function() {
            //獲得滾動條到頂部的距離
            Ontop = document.documentElement.scrollTop || document.body.scrollTop;//兼容性設置;
            if (Ontop > clientH * 2) {
                divs.style.display = "block";
            } else {
                divs.style.display = "none";
            }
            toTop(); //調用回到頂部函數;
        }
		
		//回到頂部函數;
		function toTop(){
			divs.onclick = function(){
			timer = setInterval(function(){ 	
				//讓滾動條到頂部的距離自動縮減到0;
				document.documentElement.scrollTop = document.body.scrollTop = Math.floor(Ontop - 200);//兼容性設置;
				//設置定時器
					if(Ontop === 0 || document.documentElement.scrollTop === 0){
						clearInterval(timer);
					}
				},10);
			}
		}
	}

注:
其實,就是對常見的window對象和document對象的一些使用;

  • 可視區域的寬、高:
    document.documentElement.clientHeight;
    document.documentElement.clientWidth;

  • 滾動條的相關信息:
    document.documentElement.scrollTop;
    document.body.scrollTop(IE兼容);

  • 計時器的使用和清除:
    setInterval();
    clearInterval();

  • Math對象(向下舍入)
    Math.floor();

  • window.onscroll:滾動條事件(滾動時觸發);

~如遇錯誤,歡迎指正;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章