js网页返回页面顶部的小方法

时间:2021-11-30 09:12:50

咳咳,在网页出现滚动条的时候,许多网站会在右下角出现一个图标,点击可以回到页面顶部

本文就记录下js实现代码:

1.在html页面body添加dom元素

<img src="toTop.png" alt="" 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" 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();
}
}) //点击返回顶部
$(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