# [HTML] a Anchor Link 滑順捲動(scroll-behavior、scrollIntoView) ###### tags: `HTML` `CSS` `JavaScript` `Web API` `<a>`的目標連結若為同頁面上的指定 id,點擊時會直接跳到指定 id 的位置,視覺上不夠順暢,操作體驗較差。為改善此狀況,可選擇 CSS 或 JavaScript 處理。 ## CSS ### scroll-behavior :::info * [W3C CSS Overflow Module Level 3 smooth-scrolling](https://drafts.csswg.org/css-overflow/#smooth-scrolling) * [MDN scroll-behavior](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior) ::: :::warning 目前主流瀏覽器皆有支援,但 Safari 在 15.4 版才能使用(Release date:2022-03-14),完整支援度可查閱 [Can I use...](https://caniuse.com/css-scroll-behavior) ::: #### 值 * auto:立刻移動到指定位置,視覺上像是瞬間跳過去 * smooth:滑順移動到指定位置,視覺上是順暢地滑動過去 #### 寫法 在產生捲軸的元素加上 `scroll-behavior: smooth;` ```css= html { scroll-behavior: smooth; } ``` ## JavaScript ### scrollIntoView :::info * [W3C CSSOM View Module dom-element-scrollintoview](https://drafts.csswg.org/cssom-view/#dom-element-scrollintoview) * [MDN Element: scrollIntoView() method](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) * [那些被忽略但很好用的 Web API / ScrollIntoView](https://ithelp.ithome.com.tw/articles/10279669) ::: :::warning 目前主流瀏覽器皆有支援,但 Safari 在 15.4 版才能使用 smooth(Release date:2022-03-14),完整支援度可查閱 [Can I use...](https://caniuse.com/scrollintoview) ::: #### 值 * boolean: * true:預設值。等同`{ block: 'start', inline: 'nearest' }` * false:等同`{ block: 'end', inline: 'nearest' }` * behavior:捲動方式 * smooth:滑順移動 * instant:立刻移動 * auto:預設值。由 scroll-behavior 的值決定捲動方式 * block:垂直對齊位置 * start:預設值 * center * end * nearest * inline:水平對齊位置 * start * center * end * nearest:預設值 #### 寫法 ```javascript= document.querySelectorAll('a[href^="#"]').forEach((el) => { el.addEventListener('click', (e) => { e.preventDefault(); document.querySelector(el.getAttribute('href')).scrollIntoView({ behavior: 'smooth', }); }); }); ``` ## 參考資料 * [Smooth scrolling when clicking an anchor link](https://stackoverflow.com/questions/7717527/smooth-scrolling-when-clicking-an-anchor-link) --- :::info 建立日期:2023-05-28 更新日期:2023-05-28 :::