js 锚点定位的简单方法

1,040 阅读1分钟

使用scrollIntoView方法进行定位到某一位置

最近在segmentfault中看到了这个简单方法,就是用scrollIntoView方法就可以实现锚点定位,非常简单,在此记录一下

可以直接使用(当然像在vue中也可以使用ref获取dom)

	// 如果为true,元素的顶端将和其所在滚动区的可视区域的顶端对齐。

	// 如果为false,元素的底端将和其所在滚动区的可视区域的底端对齐。

	document.querySelector('#需要定位的ID').scrollIntoView(true)

也可以配置参数定位的位置和动画效果

	document.querySelector('#需要定位的ID').scrollIntoView({

	  behavior: "smooth", // 定义动画过渡效果, "auto""smooth" 之一。默认为 "auto"

	  block: "center", // 定义垂直方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "start"

	  inline: "nearest" // 定义水平方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "nearest"

	})

传统的锚点定位

html本身就有锚点定位的功能,在html页面内可以设置锚点,通过a链接进行跳转即可

如html中定义一个锚点,这里可以用name或者id

	<ul>

	  <li id="anchor1">锚点1</li>

	  <li id="anchor2">锚点2</li>

	  <li id="anchor3">锚点3</li>

	</ul>

锚点使用

	<a href="#anchor1">跳至第一个锚点</a>

在js中可以通过location跳转

	window.location.href = "#anchor1" // 跳至第一个锚点

	// 或者

	window.location.hash = "#anchor1" // 跳至第一个锚点