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

1、原理javascript

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

2、实现代码css

<!DOCTYPE HTML>html

<html>java

<head>jquery

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

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

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

</head>动画

<body>ui

<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>

相关文章
相关标签/搜索