一、設計思路:
1、為返回頂部的a標簽添加滾動事件。
2、獲取當前窗口的滾動條位置,當滾動條的位置處於距頂部50像素以下時,跳轉鏈接出現,否則消失
3、為圖標添加點擊事件,使用animate動畫效果設置滾動條回到頂部所需的時間。
實現效果如圖:
二、技術實現
1、html代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head> body{ height:1500px; background-color:#000; } <body>
<div>
<a href="javascript:;" id="btn" title="回到頂部"style="width:50px; height:50px; position:fixed; right:50px; bottom:10px; background:url('自己的圖片url') no-repeat;">
</a>
</div>
</body>
</html>
2、jquery代碼
<script type="text/javascript" str="自己的jquery.min.js文件所在地址"> $(document).ready(function() { //首先將#btn隱藏
$("#btn").hide(); //當滾動條的位置處於距頂部50像素以下時,跳轉鏈接出現,否則消失
$(function() { $(window).scroll(function() { if ($(window).scrollTop() > 50) { $("#btn").fadeIn(200); } else { $("#btn").fadeOut(200); } }); //當點擊跳轉鏈接后,回到頁面頂部位置
$("#btn").click(function() { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); }); }); </script>