加入css樣式
- #back-top {
- position: fixed;
- bottombottom: 30px;
- margin-left: -150px;
- }
- #back-top a {
- width: 108px;
- display: block;
- text-align: center;
- font: 11px/100% Arial, Helvetica, sans-serif;
- text-transform: uppercase;
- text-decoration: none;
- color: #bbb;
- /* transition */
- -webkit-transition: 1s;
- -moz-transition: 1s;
- transition: 1s;
- }
- #back-top a:hover {
- color: #000;
- }
- /* arrow icon (span tag) */
- #back-top span {
- width: 108px;
- height: 108px;
- display: block;
- margin-bottom: 7px;
- background: #ddd url(up-arrow.png) no-repeat center center;
- /* rounded corners */
- -webkit-border-radius: 15px;
- -moz-border-radius: 15px;
- border-radius: 15px;
- /* transition */
- -webkit-transition: 1s;
- -moz-transition: 1s;
- transition: 1s;
- }
- #back-top a:hover span {
- background-color: #777;
- }
加入js部分
- <script>
- $(document).ready(function(){
- $("#back-top").hide();//首先將返回頂部這個圖片隱藏
- // 淡入返回頂部圖片
- $(function () {
- $(window).scroll(function () {
- if ($(this).scrollTop() > 100) {
- $('#back-top').fadeIn();//如果鼠標滾動頁面的距離頂部大於100像素時以淡入的方式顯示返回頂部圖片
- } else {
- $('#back-top').fadeOut();//如果小於100像素則隱藏圖片
- }
- });
- // 當鼠標點擊返回頂部圖片時
- $('#back-top a').click(function () {
- $('body,html').animate({
- scrollTop: 0 //返回到距離頁面頂部0像素的位置
- }, 800); //以800毫秒的速度向上滾動
- return false;
- });
- });
- });
- </script>
最後一步在body標籤內加入id="top",即<body id="top">添加一個錨點,當鼠標點擊返回頂部鏈接時,即之前添加過的
<p id="back-top">
< a href="#top"><span></span>Back to Top</a>
< /p>
就可以順利返回頂部了