錨點定位及返回頂部
阿新 • • 發佈:2019-02-20
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery.1.9.1.min.js"></script> </head> <body> <div class="header"> <div class="header-width"> <ul class="nav fr" > <li class="list list2"> <a href="javascript:void(0)">頭部</a> </li> <li class="list list2"> <a href="javascript:void(0)" to="main-one">錨點1</a> </li> <li class="list list3"> <a href="javascript:void(0)" to="main-two">錨點2</a> </li> <li class="list list4""> <a href="javascript:void(0)" to="main-three">錨點3</a> </li> </ul> </div> <div style="height: 800px" id="main-one">main-one</div> <div style="height: 800px" id="main-two">main-two</div> <div style="height: 1200px" id="main-three">main-three</div> <div class="gototop" style="position: fixed;right: 100px;bottom: 100px">返回頂部</div> </div> <script> $(function () { // 錨點定位 $('.header .list a').click(function () { var id = $(this).attr('to'); var top = $("#" + id).offset().top ; $("html, body").animate({ scrollTop: top }, { duration: 500, easing: "swing" }); return false; }); // 滾動事件 $(window).scroll(function(){ var windowH= $(window).height(); var scrollTop = $(window).scrollTop(); // 導航欄 if(scrollTop>300){ $('.gototop').css("display","block"); }else{$('.gototop').css("display","none");} }); // 點選返回頂部 $('.gototop').click(function () { $("html, body").animate({scrollTop: 0}, 500); }); }) </script> </body> </html>