很多的網頁都習慣在右下角做一個可以回捲到最上方的按鈕,這個功能的其實原理很簡單,只要善用scroll系列的函式即可達到效果
HTML
CSS
.return-btn { width:40px; height:40px; background:#000; border-radius:20px; font-size:25px; text-align:center; position:fixed; right:30px; bottom:30px; padding-top:5px; padding-right:1px; } .return-btn a { color:#FFF; display:block; }
jQuery
(function() { ('.return-btn').hide(); (window).scroll(function() { if ((this).scrollTop()) { //當scrollTop不等於0(不在最上方,顯示button) ('.return-btn').stop(true, true).fadeIn(); } else { //當scrollTop等於0(在最上方,隱藏button) ('.return-btn').stop(true, true).fadeOut(); } }); ('.return-btn').click(function(e) { e.preventDefault(); //移回最上方 ('html, body').animate({scrollTop:0}, 500); }); });
Categories: jQuery