標籤:java 源碼 idt center display scrolltop style min click
咳咳,在網頁出現捲軸的時候,許多網站會在右下角出現一個表徵圖,點擊可以回到頁面頂部
本文就記錄下js實現代碼:
1.在html頁面body添加dom元素
<img src="toTop.png" class="gotop" ><div class="gotopdiv" style="display: none;"><span>返回頂部</span></div>
2.頁面向下滾動時,出現該表徵圖
//滾動時出現返回頂部 $(window).scroll(function () { var top_scroll = $(document).scrollTop(); if (top_scroll > 0) { $(‘img.gotop‘).css({ ‘display‘: ‘block‘, ‘cursor‘: ‘pointer‘ }); $(‘.gotopdiv‘).css({ ‘display‘: ‘none‘ }); } else { $(‘img.gotop,.gotopdiv‘).css({ ‘display‘: ‘none‘ }) } })
3.點擊該表徵圖,回到頁面頂端
//點擊返回頂部 $(document).on(‘click‘,‘.gotopdiv,.gotop‘,function () { $(document).scrollTop(0); $(‘.gotop‘).hide() $(‘.gotopdiv‘).hide(); })
4.加入該表徵圖滑鼠放置離開css效果
$(document).on(‘mouseenter‘,‘.gotop‘,function () { var top_scroll = $(document).scrollTop(); if (top_scroll > 0) { $(this).next().show(); $(this).hide(); } }) $(document).on(‘mouseleave‘,‘.gotopdiv‘,function () { var top_scroll = $(document).scrollTop(); if (top_scroll > 0) { $(this).prev().show() $(this).hide(); } })
5 加入css。頁面最終全部代碼如下:
<!doctype html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <script src="jquery-1.10.2.min.js"></script><style>.gotop,.gotopdiv{ position: fixed; bottom: 20px; width: 52px; display: none; height: 52px; right: 100px; z-index: 999; }.gotopdiv{ background: #60BF8B; font-weight: bold; text-align: center; cursor: pointer; width: 52px; height: 55px; color: #fff; font-size: 15px;}.gotopdiv span{display: inline-block;padding: 10px;position: relative;}</style></head><body><div style="position:absolute;width:600px;height:3000px;"></div><img src="toTop.png" class="gotop" ><div class="gotopdiv" style="display: none;"><span>返回頂部</span></div></body><script> $(document).on(‘mouseenter‘,‘.gotop‘,function () { var top_scroll = $(document).scrollTop(); if (top_scroll > 0) { $(this).next().show(); $(this).hide(); } }) $(document).on(‘mouseleave‘,‘.gotopdiv‘,function () { var top_scroll = $(document).scrollTop(); if (top_scroll > 0) { $(this).prev().show() $(this).hide(); } }) //點擊返回頂部 $(document).on(‘click‘,‘.gotopdiv,.gotop‘,function () { $(document).scrollTop(0); $(‘.gotop‘).hide() $(‘.gotopdiv‘).hide(); }) //滾動時出現返回頂部 $(window).scroll(function () { var top_scroll = $(document).scrollTop(); if (top_scroll > 0) { $(‘img.gotop‘).css({ ‘display‘: ‘block‘, ‘cursor‘: ‘pointer‘ }); $(‘.gotopdiv‘).css({ ‘display‘: ‘none‘ }); } else { $(‘img.gotop,.gotopdiv‘).css({ ‘display‘: ‘none‘ }) } })</script></html>
Demo效果和源碼下載可以點擊demo
js網頁返回頁面頂部的小方法