【前端案例】 20 - 案例:返回顶部
2020-12-22 本文已影响0人
itlu
案例演示
返回顶部功能分析
-
带有动画的返回顶部;
-
此时可以继续使用我们封装的动画函数;
-
只需要把所有的
left
相关的值改为 跟 页面垂直滚动距离相关就可以了; -
页面滚动了多少,可以通过
window.pageYOffset
得到; -
最后是页面滚动,使用
window.scroll(x,y)
。
代码实现
html
<div class="slider_bar">
<div class="goBack ">返回顶部</div>
</div>
<div class="header w fontStyle">头部区域</div>
<div class="banner w fontStyle">banner区域</div>
<div class="main w fontStyle">主体区域</div>
css
* {
padding: 0;
margin: 0;
}
.fontStyle {
font-size: 25px;
text-align: center;
font-weight: 700;
}
.w {
width: 1200px;
margin: 10px auto;
}
.header {
height: 150px;
line-height: 150px;
background-color: skyblue;
}
.banner {
height: 220px;
line-height: 220px;
background-color: honeydew;
}
.main {
height: 1200px;
line-height: 1200px;
background-color: seashell;
}
/* 侧边栏的编写 */
.slider_bar {
position: absolute;
left: 50%;
top: 300px;
margin-left: 650px;
width: 45px;
height: 130px;
background-color: deepskyblue;
}
.goBack {
position: absolute;
display: none;
bottom: 0;
cursor: pointer;
}
javascript
/**
* 1. 事件源是document
*
* 2. 页面被卷去的头部 window.pageYOffset
*
* 3. 获取banner的offsetTop
*/
let slider_bar = document.querySelector('.slider_bar');
let banner = document.querySelector('.banner');
let bannerTop = banner.offsetTop;
let goBack = document.querySelector('.goBack');
let sliderBarTop = (slider_bar.offsetTop - bannerTop);
let main = document.querySelector('.main');
let mainTop = main.offsetTop;
// 页面滚动事件
// document.documentElement 获取的是页面的根元素 html
document.addEventListener('scroll', function () {
// 页面滚动事件
// console.log('666');
// 获取当前页面距离顶部的距离
// if ()
if (pageYOffset >= bannerTop) {
// 将 goBack 设置为固定定位
slider_bar.style.position = 'fixed';
// 避免跳动
slider_bar.style.top = sliderBarTop + 'px';
} else {
slider_bar.style.position = 'absolute';
slider_bar.style.top = '300px';
}
// 当页面滚动到main主体部分显示返回顶部
// pageYOffset 有严重的兼容性问题
if (pageYOffset >= mainTop) {
goBack.style.display = 'block';
} else {
goBack.style.display = 'none';
}
});
// 返回顶部使用的是window.scroll(x,y)
goBack.addEventListener('click', () => {
// 比较突兀的方式
// window.scroll(0, 0)
// 使用动画的方式
// 需要使用的对象是 window
animation(window, 0);
});
/**
* 修改动画为垂直方向移动的
* @param ele
* @param target
* @param callback
*/
function animation(ele, target, callback) {
// 在每次设置定时器之前清除对象中的默认定时器
// 注意1
clearInterval(ele.timer);
ele.timer = setInterval(() => {
// 计算缓动动画 步长
let step = (target - ele.pageYOffset) / 10;
// 判断如果是正值就向上取整 , 如果是负值就向下取整
// 注意2
step = step > 0 ? Math.ceil(step) : Math.floor(step);
// 移动盒子
// ele.style.left = ele.pageYOffset + step + 'px';
// 使用 window.scroll 实现页面缓慢的移动
window.scroll(0, ele.pageYOffset + step);
// 判断当前是否超出目标值 如果超出就清除定时器
if (ele.pageYOffset === target) {
clearInterval(ele.timer);
// 在清除定时器之后 需要执行一个回调函数
// 注意3
if (callback) {
callback();
}
}
}, 10);
}