jQuery 按鈕讓網頁快速回到最上方

jquery

早期在筆者在做活動網頁的時候,會用到一些jq的一些效果與技巧,增強使用者體驗。

最近在做個人外網有用到這項效果,稍微記錄一下


先加入這個往上的按鈕css

#gotop {
 /*go to top btn css*/
 display: none;
 position: fixed;
 right: 20px;
 bottom: 20px;
 padding-top: 20px;
 padding-bottom:12px;
 font-size: 20px;
 background-color: #0cac00;
 color: white;
 cursor: pointer;
 width: 70px;
 height: 30px;
 text-align: center;
}

然後再放入go top的div物件
 

<div id="gotop">go top</div>

然後開始撰寫

$(function(){
    //按下gotop的事件處理
   	$("#gotop").click(function(){
		jQuery("html,body").animate({scrollTop:0},1000);
    });
    //下滑出現到300,就出現gotop
	$(window).scroll(function() {
	  if ( $(this).scrollTop() > 300){
		$('#gotop').fadeIn();
	  } else {
		$('#gotop').fadeOut();
	  }
	});
});

 

老E隨手寫