js网页返回页面顶部的小方法
生活随笔
收集整理的這篇文章主要介紹了
js网页返回页面顶部的小方法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
咳咳,在網(wǎng)頁(yè)出現(xiàn)滾動(dòng)條的時(shí)候,許多網(wǎng)站會(huì)在右下角出現(xiàn)一個(gè)圖標(biāo),點(diǎn)擊可以回到頁(yè)面頂部
本文就記錄下js實(shí)現(xiàn)代碼:
1.在html頁(yè)面body添加dom元素
<img src="toTop.png" alt="" class="gotop" ><div class="gotopdiv" style="display: none;"><span>返回頂部</span></div>?2.頁(yè)面向下滾動(dòng)時(shí),出現(xiàn)該圖標(biāo)
//滾動(dòng)時(shí)出現(xiàn)返回頂部$(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.點(diǎn)擊該圖標(biāo),回到頁(yè)面頂端
//點(diǎn)擊返回頂部$(document).on('click','.gotopdiv,.gotop',function () {$(document).scrollTop(0);$('.gotop').hide()$('.gotopdiv').hide();})4.加入該圖標(biāo)鼠標(biāo)放置離開(kāi)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。頁(yè)面最終全部代碼如下:
<!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" alt="" 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();}})//點(diǎn)擊返回頂部$(document).on('click','.gotopdiv,.gotop',function () {$(document).scrollTop(0);$('.gotop').hide()$('.gotopdiv').hide();})//滾動(dòng)時(shí)出現(xiàn)返回頂部$(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效果和源碼下載可以點(diǎn)擊demo
轉(zhuǎn)載于:https://www.cnblogs.com/mengsx/p/6135040.html
總結(jié)
以上是生活随笔為你收集整理的js网页返回页面顶部的小方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 2016年12月数据库流行度排行榜
- 下一篇: Object类.