页面回到顶部的实现及原理

笑着哭i 提交于 2019-12-09 20:26:47

一、原理

  • 监听当前页面滚动事件
  • 当滚动到一定像素显示回到顶部的按钮
  • 给回到顶部按钮绑定点击事件,点击按钮让滚动条回到顶部并隐藏按钮

二、实现代码

<!DOCTYPE HTML>

<html>

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

<title>回到顶部demo</title>

<style type="text/css"> .up{ position:fixed; bottom:20px; right:20px; width:10px; display:none; } </style>

</head>

<body>

<div style="background:rgb(200,200,200);height:2000px;">我很长</div>

<a id="up" href="javascript:;" class="up">回到顶部</a>

</body>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type="text/javascript">

//绑定页面滚动事件

$(window).bind('scroll',function(){

var len=$(this).scrollTop(); 

if(len>=100){

//显示回到顶部按钮

$('#up').show();

}else{

//影藏回到顶部按钮

$('#up').hide();

}

})

 

//绑定回到顶部按钮的点击事件

$('#up').click(function(){

//动画效果,平滑滚动回到顶部

$(document).animate({ scrollTop: 0 });

//不需要动画则直接

//$(document).scrollTop(0) })

</script>

</html>

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!