小火箭回傳頂部案例
1. 滾動頁面,當頁面距離頂部超出1000px,顯示小火箭,
封裝在scroll函式里,當前頁面距離頂部為$(window).scrollTop >=1000
小火箭顯示和隱藏用fadeIn和fadeOut
//當頁面超出1000px的時候,讓小火箭顯示,如果小于1000px,則隱藏 $(window).scroll(function () { if ($(window).scrollTop() >= 1000) { $(".actGotop").stop().fadeIn(1000); } else { $(".actGotop").stop().fadeOut(1000); } }) });
2. 當小火箭出現后,點擊小火箭,回傳到頁面頂部,
在外面出冊點擊事件,獲取頁面,html或者body, 回傳用animate影片函式,到頂部即scrollTop為0,時間可以設定
$(".actGotop").click(function () {
$("html,body").stop().animate({ scrollTop: 0 }, 1000);
});
3. 如果要讓小火箭點擊后,直接回到頂部,可以只設定$(window).scrollTop(0),既可
$(".actGotop").click(function () {
//$("html,body").stop().animate({ scrollTop: 0 }, 1000);
//scrollTop為0
$(window).scrollTop(0);
});
整體代碼如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body { height: 8000px; } a { color: #FFF; } .actGotop { position: fixed; bottom: 50px; right: 50px; width: 150px; height: 195px; display: none; z-index: 100; } .actGotop a, .actGotop a:link { width: 150px; height: 195px; display: inline-block; background: url(images/gotop.png) no-repeat; outline: none; } .actGotop a:hover { width: 150px; height: 195px; background: url(images/gotop.gif) no-repeat; outline: none; } </style> </head> <body> <!-- 回傳頂部小火箭 --> <div class="actGotop"><a href="javascript:;" title="Top"></a></div> <script src="jquery-1.12.4.js"></script> <script> $(function () { //當頁面超出1000px的時候,讓小火箭顯示,如果小于1000px,則隱藏 $(window).scroll(function () { if ($(window).scrollTop() >= 1000) { $(".actGotop").stop().fadeIn(500); } else { $(".actGotop").stop().fadeOut(500); } }) }); //在外面注冊 $(".actGotop").click(function () { $("html,body").stop().animate({ scrollTop: 0 }, 1000); //scrollTop為0 // $(window).scrollTop(0); }); </script> </body> </html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/14850.html
標籤:jQuery
