html 锚点平滑滚动到目标位置

阅读数:16 评论数:0

跳转到新版页面

分类

html/css/js

正文

// 获取所有的锚点链接元素
const anchorLinks = document.querySelectorAll('a[href^="#"]');

// 给每个锚点链接添加点击事件处理程序
anchorLinks.forEach(link => {
	link.addEventListener('click', e => {
		e.preventDefault(); // 阻止默认的锚点跳转行为

		// 获取目标元素的ID
		const targetId = link.getAttribute('href');
		console.log(targetId)

		// 获取目标元素
		const targetElement = document.querySelector(targetId);

		// 使用scrollIntoView方法实现平滑滚动效果
		targetElement.scrollIntoView({
			behavior: 'smooth',
			block: 'start' // 滚动到目标元素顶部
		});
	});
});

一、scroll-behavior

html {
  scroll-behavior: auto | smooth;
}
auto(默认) 该值允许滚动框中的元素之间突然跳转。
smooth 该值是滚动框内元素之间的平滑的过渡动画。

二、scrollIntoView

将调用它的元素滚动到浏览器窗口的可见区域。

element.scrollIntoView(); // 等同于element.scrollIntoView(true)
element.scrollIntoView(alignToTop); //布尔参数
element.scrollIntoView(scrollIntoViewOptions); //对象参数

1、alignToTop

true

元素的顶部将对齐到可滚动祖先的可见区域的顶部。

对应于scrollIntoViewOptions: {block: “start”, inline: “nearest”}。

这是默认值

false

元素的底部将与可滚动祖先的可见区域的底部对齐。

对应于scrollIntoViewOptions: {block: “end”, inline: “nearest”}。

2、scrollIntoViewOptions

behavior [可选]定义过渡动画。“auto”,“instant"或"smooth”。默认为"auto"。
block [可选] “start”,“center”,“end"或"nearest”。默认为"center"。
inline [可选] “start”,“center”,“end"或"nearest”。默认为"nearest"。



相关推荐