文章目录
在 WHAT - 前端开发滚动条场景解析 我们已经介绍过一些比较经典的滚动条场景,今天主要学习涉及的API。
在前端开发中,涉及“滚动”操作的 API 非常丰富,主要分为以下几类:
一、获取/设置滚动位置
1. window.scrollX / window.scrollY
- 返回页面在 X/Y 方向的滚动偏移量(单位:像素)
2. element.scrollTop / element.scrollLeft
- 获取或设置某个元素在垂直/水平方向上的滚动距离。
二、滚动控制(滚动到某个位置)
3. window.scrollTo(x, y)
-
将窗口滚动到指定位置
window.scrollTo(0, 0); // 回到页面顶部
4. window.scrollBy(dx, dy)
-
相对于当前滚动位置滚动一定的距离
window.scrollBy(0, 100); // 向下滚动 100px
5. element.scrollTo(options) (支持平滑滚动)
-
滚动容器元素到某个位置
element.scrollTo({ top: 100, behavior: 'smooth' });
6. element.scrollIntoView(options?)
-
将元素滚动到视口可见区域
document.querySelector('#target').scrollIntoView({ behavior: 'smooth' });
三、滚动事件监听
7. scroll 事件
-
监听页面滚动行为(节流/防抖推荐)
window.addEventListener('scroll', () => { console.log(window.scrollY); });
四、滚动高度与容器尺寸
8. element.scrollHeight / element.scrollWidth
- 内容的总高度/宽度(包括看不见的部分)
9. element.clientHeight / element.clientWidth
- 可见区域高度/宽度(不含滚动条)
10. element.offsetHeight / offsetWidth
- 元素的可见大小(包括内边距和边框)
具体区别可以看如下示例图:
五、Intersection Observer(可视区域监听)
11. IntersectionObserver
-
判断元素是否出现在视口内,适用于懒加载、无限滚动等场景。
const observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { console.log('元素进入视口'); } }); }); observer.observe(document.querySelector('#target'));
六、Scroll Snap(CSS)
scroll-snap-type
,scroll-snap-align
等 CSS 属性,用于实现滚动吸附。
这些属性能让滚动容器在滚动停止时自动“吸附”到指定的子元素位置,提升用户体验,常用于:
- 横向滑动图集(如轮播图)
- 全屏滚动页面(如 PPT 效果)
- 滚动选择器(如时间选择)
基本属性说明
scroll-snap-type
- 设置在滚动容器(父元素)上,定义滚动的方向和吸附方式。
.scroll-container {
scroll-snap-type: x mandatory; /* 横向吸附,强制 */
overflow-x: scroll;
}
-
常用值:
x
,y
,block
,inline
,both
:吸附方向mandatory
:必须吸附(强吸附)proximity
:靠近才吸附(弱吸附)
scroll-snap-align
- 设置在子元素上,定义该元素在视口中的对齐方式。
.scroll-item {
scroll-snap-align: start; /* 元素头部与容器对齐 */
}
-
常用值:
start
:顶部或左边对齐center
:居中对齐end
:底部或右边对齐
实例代码:横向吸附滚动
<div class="scroll-container">
<div class="scroll-item">1</div>
<div class="scroll-item">2</div>
<div class="scroll-item">3</div>
</div>
.scroll-container {
display: flex;
overflow-x: auto;
scroll-snap-type: x mandatory;
scroll-behavior: smooth;
width: 100%;
}
.scroll-item {
flex: 0 0 100%;
scroll-snap-align: start;
height: 100vh;
background: lightgray;
border: 1px solid #ccc;
}
更具体的解释和demo可以阅读:https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-type
七、CSS 滚动行为控制
/* 启用平滑滚动 */
html {
scroll-behavior: smooth;
}
更具体的内容可以阅读:WHAT - 滚动条 css scrollbar-* 属性