1、問題
由於vue 路由hash模式在url中已經將#占用,頁面上的#已經不具備hash 錨點功能。
2、js實現帶動畫的錨點定位
goAnchor (selector) { var anchor = document.querySelector(selector) // 沒有動畫
// document.documentElement.scrollTop = anchor.offsetTop
// 有動畫
this.scrollTo(anchor.offsetTop, 500) }, scrollTo (y, duration) { /* y:目標縱坐標,duration:時間(毫秒) */
var scrollTop = document.body.scrollTop /* 頁面當前滾動距離 */
var distance = y - scrollTop /* 結果大於0,說明目標在下方,小於0,說明目標在上方 */
var scrollCount = duration / 10 /* 10毫秒滾動一次,計算滾動次數 */
var everyDistance = parseInt( distance / scrollCount ) /* 滾動距離除以滾動次數計算每次滾動距離 */
for ( var index = 1; index <= scrollCount; index++ /* 循環設置scrollBy事件,在duration之內,完成滾動效果 */ ) { setTimeout(function () { window.scrollBy(0, everyDistance) }, 10 * index) } let deviation = y - scrollCount * everyDistance window.scrollBy(0, deviation) }
html:
<span class="anchor anchor1 active" @click="goAnchor('#anchor1')"> 首頁 </span>