码迷,mamicode.com
首页 > 其他好文 > 详细

回到顶部带动画

时间:2020-04-07 20:30:21      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:属性   play   ret   方式   ntb   回到顶部   targe   目标   lse   

// 获取元素
var bodyTop = document.getElementById("top");
// 回到顶部的按钮
var totop = document.getElementById("totop");
// top 是window自带的一个属性,此属性是只读的。此属性默认是window对象
// 当拖动滚动条的时候执行
window.onscroll = function () {
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
//1 当拖动滚动条的时候,当内容滚动出去 10px的时候,改变top的高度,并且显示回到顶部按钮
if (scrollTop > 10) {
// 改变top
bodyTop.className = ‘header fixed‘;
// 显示回到顶部
totop.style.display = ‘block‘;
} else {
// 改变top
bodyTop.className = ‘header‘;
// 显示回到顶部
totop.style.display = ‘none‘;
}
}

//2 当点击回到顶部按钮的时候,动画的方式,回到最上面,让滚动距离为0
var timerId = null;
totop.onclick = function () {
if (timerId) {
clearInterval(timerId);
timerId = null;
}
timerId = setInterval(function () {
// 步进 每次移动的距离
var step = 10;
// 目标位置
var target = 0;
// 获取当前位置
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
var current = scrollTop;
if (current > target) {
step = -Math.abs(step);
}
// 判断当前是否到达目标位置
if (Math.abs(current - target) <= Math.abs(step)) {
clearInterval(timerId);
document.body.scrollTop = target;
document.documentElement.scrollTop = target;
return;
}

current += step;
document.body.scrollTop = current;
document.documentElement.scrollTop = current;
}, 5);
}

回到顶部带动画

标签:属性   play   ret   方式   ntb   回到顶部   targe   目标   lse   

原文地址:https://www.cnblogs.com/pxxdbk/p/12655365.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!