# HTML页面锚点定位
1 min read
Table of Contents
在 HTML 页面内实现锚点定位和跳转。
<a> 标签
通过 a 标签和 ID 选择器实现锚点和页面跳转。对应的 URL 会进行变化。
<a href="#A">A</a><a href="#B">B</a><a href="#C">C</a>
<h1 id="A">A</h1><div style="height: 800px"></div><h1 id="B">B</h1><div style="height: 800px"></div><h1 id="C">C</h1><div style="height: 800px"></div>实例代码:锚点跳转-a 标签
scrollIntoView
使用元素的 scrollIntoView 来实现页面的滚动。该方法不会改变对应的 URL。
可以通过指定参数 { behavior: "smooth" } 来实现页面的滚动动画。
<button id="btnA">A</button><button id="btnB">B</button><button id="btnC">C</button>
<h1 id="A">A</h1><div style="height: 800px"></div><h1 id="B">B</h1><div style="height: 800px"></div><h1 id="C">C</h1><div style="height: 800px"></div>const A = document.getElementById('btnA')const B = document.getElementById('btnB')const C = document.getElementById('btnC')
function handleClick(id) { document.getElementById(id).scrollIntoView()}
A.addEventListener('click', () => handleClick('A'))B.addEventListener('click', () => handleClick('B'))C.addEventListener('click', () => handleClick('C'))实例代码:锚点跳转-scrollIntoView