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

原生js实现返回顶部缓冲效果

2017-01-18 16:38 901 查看

运行原理

通过定时器30毫秒执行一次滚动条上升,每次上升的高度为当前高度的80%,这样就达到了上升缓冲的动画效果。

判断当滚动条高度超过一屏时,按钮显示,默认隐藏

知识要点

scrollTop//获取滚动条高度 需要写兼容
clientHeight//可视窗口高度 需要写兼容
setInterval//定时器
window.onscroll//滚动触发事件

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>demo</title>
<style>
body,h1,h2,h3,h4,h5,h6,hr,p,blockquote,dl,dt,dd,ul,ol,li,pre,form,fieldset,legend,button,input,textarea,th,td{margin:0;padding:0;}
h1,h2,h3,h4,h5,h6{font-size:100%;}
address,cite,dfn,em,var{font-style:normal;}
code,kbd,pre,samp{font-family:courier new,courier,monospace;}
ul,ol{list-style:none;}
a{text-decoration:none;}
a:hover{text-decoration:none;}
sup{vertical-align:text-top;}
sub{vertical-align:text-bottom;}
legend{color:#000;}
fieldset,img{border:0;}
button,input,select,textarea{font-size:100%;}
table{border-collapse:collapse;border-spacing:0;}
.clear{clear: both;float: none;height: 0;overflow: hidden;}
.bg{background:#9B1BC5; width: 1000px; height: 3000px; margin: 0 auto;}
#gotop{width: 50px; height: 50px; background:#5490F5; color: #fff; position: fixed; left: 50%; bottom: 30px; text-align: center; font-family: "Microsoft Yahei",tahoma,arial; font-size: 14px; cursor: pointer; margin-left: 520px; display: none;}
#gotop span{display: block;padding: 5px;}
</style>
</head>
<body>
<div class="bg"></div>
<div id="gotop"><span>返回顶部</span></div>
<script type="text/javascript">
//在页面加载完后立即执行多个函数方案
function addloadEvent(func){
var oldonload=window.onload;
if(typeof window.onload !="function"){
window.onload=func;
}
else{
window.onload=function(){
if(oldonload){
oldonload();
}
func();
}
}
}
//在页面加载完后立即执行多个函数方案结束
addloadEvent(b);
function b(){
var gotop=document.getElementById("gotop");
var timer;
var tf=true;
//滚动触发
window.onscroll=function(){
//获取滚动条高度
var ostop=document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
//获取窗口可视区域高度
//console.log(ostop)
var ch=document.documentElement.clientHeight||document.body.clientHeight;
//如果页面超过一屏高度按钮显示,否则隐藏
if(ostop>=ch){
gotop.style.display="block";
}else{
gotop.style.display="none";
}
//
if(!tf){
clearInterval(timer);
}
tf=false;
}
//点击触发
gotop.onclick=function(){
//创建定时器
timer=setInterval(function(){
//获取滚动条高度
var ostop=document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
//每次上升高度的20%
var speed=Math.ceil(ostop/5);
//每次上升当前高度的80%
document.documentElement.scrollTop=document.body.scrollTop=ostop-speed;
//如果高度为0,清除定时器
if(ostop==0){
clearInterval(timer);
}
tf=true;
},30);
}
}
</script>
</body>
</html>

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本之家!

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js 返回顶部