- 作者:陈大鱼头
- github: KRISACHAN
前言
在日常的开发中,我们对 scroll
这个单词肯定不陌生。
例如因为看不惯浏览器默认样式而用 JS 一顿猛如虎操作的 自定义滚动条 。
或者是嗖~一下就到顶的 回到顶部 。
又或者是想去哪点哪的 标题导航 。
但是在过去的开发中,要实现这些功能并不是那么轻松的一件事情。
例如我们要实现一个有滚动效果的 回到顶部 功能,我们可能需要写下这些代码
let timer = null;
let backTop = document.querySelector("#backTop");
backTop.addEventListener("click", () => {
cancelAnimationFrame(timer);
let startTime = +new Date();
let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
let totalTime = 300;
timer = requestAnimationFrame(() => {
let lastTime = totalTime - Math.max(0, startTime - +new Date() + totalTime);
document.documentElement.scrollTop = document.body.scrollTop =
(lastTime * -scrollTop) / totalTime + scrollTop;
timer = requestAnimationFrame(func);
if (lastTime === totalTime) {
cancelAnimationFrame(timer);
}
});
});
(免责声明:伪代码未经测试,如有 BUG,跪求原谅。)
嘤,意思就是要写个动画,不断修改当前页面的垂直滚动距离,直到为 0。
(吃瓜群众:“很难嘛?是你太菜了吧,大叔!”)
但其实随着时间的推移, web api 以及 css 规范的不断改进,那些我们曾经认为实现起来很麻烦的功能也变得简单了起来。下面我们可以一起来探讨一下这些改进的内容。
Web API 中的 scroll 家族
我们来康康 scroll 家族 里有趣的 API。
scroll 与 scrollTo
scroll()
与 scrollTo
方法是用于在给定的元素中滚动到某个特定坐标的 Element 接口。
语法如下:
- scroll/scrollTo(x, y)
x
:元素要移动的位置横坐标。y
:元素要移动的位置纵坐标。
- scroll/scrollTo(options)
options
支持属性有left
,top
以及behavior
top
:元素要移动的位置横坐标。lef:
:元素要移动的位置纵坐标。behavior