您的位置:首页 > Web前端 > JavaScript

javascript之点击回到页面顶部

2017-11-09 11:58 316 查看
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>回到顶部案例</title>
<style type="text/css">
body{
height:3000px;
}
#back-top{
display: none;
position:fixed;
right: 20px;
bottom: 20px;
width: 80px;
height: 80px;
text-align: center;
line-height: 80px;
color:#fff;
background-color: rgba(0,0,0,0.5);
cursor:pointer;
transition: all .5s;
}
#back-top:hover{
background-color: rgba(0, 120, 215,0.8);
}
</style>
</head>
<body>
<div id="back-top">
回到顶部
</div>
<h1 style="text-align: center;">标题</h1>
<h3 style="margin-top:2980px;text-align: center;">底部内容</h3>
<script>
//监控文档中发生的滚动事件
document.onscroll=function(){
//获取滚动条距离顶部的位置
var st = document.body.scrollTop ||  document.documentElement.scrollTop;
if(st > 80){
//显示 回到顶部 链接
$('back-top').style.display='block';
}else{
//隐藏 回到顶部 链接
$('back-top').style.display='none';
}
}

//点击按钮返回顶部
$('back-top').onclick=function(){

timer = setInterval(function(){
//不断获取最新滚动条距离顶部的高度
var t = document.body.scrollTop ||  document.documentElement.scrollTop;
t = t- t/10;
if(t <= 0){
//结束定时任务
clearInterval(timer);
}
document.body.scrollTop = document.documentElement.scrollTop= t;
},20);
}

//简易封装
function $(id)
{
return document.getElementById(id);
}
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HTML css javascript