1.点击按钮,快速回到顶部
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'practice_02.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style type="text/css">
*{margin:0;padding:0;}
.all {
width:100%;
height:180%;
}
.btn {
position:fixed;
bottom:20px;
right:20px;
width:80px;
height:30px;
border-radius:5px;
background:red;
}
</style>
</head>
<body>
<div class="all">
<button class="btn" id="btn1">回到顶部</button>
</div>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$('#btn1').click(function() {
$('html,body').scrollTop(0);
});
</script>
</body>
</html>
2.点击按钮,缓慢的回到顶部
在这里我们来讲解一下,具体实现原理
就拿看电影来举例子,我们所看的电影都是一帧一帧播放的,肉眼对于那细小的间隔是分辨不出来的,所以我们认为电影的放映都很流畅,其实是一段一段连起来的。同样我们要实现从下到上缓慢的上升,就是一段一段的动,并且每一段都是迅速到达目的地,这样连起来就成匀速的了
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'practice_02.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style type="text/css">
*{margin:0;padding:0;}
.all {
width:100%;
height:180%;
}
.btn {
position:fixed;
bottom:20px;
right:20px;
width:80px;
height:30px;
border-radius:5px;
background:red;
}
</style>
</head>
<body>
<div class="all">
<button class="btn" id="btn1">回到顶部</button>
</div>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$('#btn1').click(function() {
//总距离
var distance = $('html').scrollTop()+$('body').scrollTop();
//height为了更新当前滚动条的高度而用
var height = $('html,body');
//总时间(500ms)
var time = 500;
//每间隔intervalTime时间滚动一次
var intervalTime = 50;
//计算每次滑动的距离
var itemDistance = distance/(time/intervalTime);
//使用循环定时器不断滚动
var intervalId = setInterval(function() {
distance -= itemDistance;
if(distance<=0) {//到达顶部,停止定时器
distance = 0;
clearInterval(intervalId);
}
//更新当前滚动条的高度
height.scrollTop(distance);
},intervalTime);
});
</script>
</body>
</html>