接上篇文章:https://www.cnblogs.com/ligulalei/p/10622778.html
在上篇文章中實現了通過使用scrollIntoView()在使用vux的移動端實現了點擊錨點進行頁面dom定位,但是這個demo在ios中運行存在兼容性問題,滑動頁面時使用position:absolute定位的dom會出現跳動現象,待有時間再解決這個bug。
好了,開始本篇內容部分:
本篇內容是在上篇內容的基礎上二次開發而來,實現了雙向定位,當頁面上下滑動到某個位置時,對應的錨點會出現高亮。看一下運行效果,還闊以吧~
為了把這個問題說清楚,我下面分4個小節分別介紹
1.找到定位坐標
在vue中使用scrollTop這個屬性總是失敗的很徹底,所以這次壓根就不在考慮使用這個玩意兒。我首先在需要滑動的內容區域找到一個定位坐標,這個參考坐標需要滿足兩點要求:
①這個坐標需要可以在頁面中上下滑動
這個坐標需要在滑動的內容區域
②這個坐標需要有個id
通過這個id,在滑動過程中可以實時監聽到這個坐標滑動到的位置,當然也可以不是id,只要能得到這個dom就行
我在這個demo中選擇的定位坐標是 id="apply1" 的div
<div id="apply1" style=" position: relative;top: -120px;display: block;height: 60;overflow: hidden;" ></div>
找到定位坐標,下面就開始監聽頁面滾動了,通過滾動頁面我們看看這個定位坐標的變化值。
2.監聽頁面滾動
監聽事件寫在 mounted 中,至於為什么寫在這里自行去了解
mounted() { window.addEventListener("scroll", this.handleScroll, true); },
這里觸發了handleScroll()事件,這個事件定義在methods:中
methods: { handleScroll(el) { }, },
3.坐標位置計算
通過在頁面滾動過程中,實時計算得到定位坐標點相對於可視屏幕頂部的高度值
代碼如下:
handleScroll(el) { let _pos = document.getElementById("apply1").getBoundingClientRect().top; console.log('top',_pos); },
在瀏覽器中運行一下,看能不能正常得到這個值:
可以看到這個值根據頁面的滾動在實時變化,ok~到這里就是萬事俱備,只欠東風了。
我們只要的到這個值,通過計算值的區域范圍就可以給錨點進行高亮顯示了。
此外我還想再多說兩句,在這里我用到了這個方法:getBoundingClientRect()
這個方法在這里做么子內?
Element.getBoundingClientRect()方法返回元素的大小及其相對於視口的位置。
瀏覽器兼容行:
參考:https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect
4.錨點高亮效果
通過得到的這個值,接下來怎么進行錨點高亮,我想你應該知道了吧。
下面是我這個demo中使用的高亮方法
methods: { handleScroll(el) { let _pos = document.getElementById("apply1").getBoundingClientRect().top; if (-88 < _pos) { this.appleNumber = 1; } if (_pos < -150) { this.appleNumber = 2; } if (_pos < -300) { this.appleNumber = 3; } if (_pos < -460) { this.appleNumber = 4; } if (_pos < -780) { this.appleNumber = 5; } if (_pos < -930) { this.appleNumber = 6; } if (_pos < -1090) { this.appleNumber = 7; } if (_pos < -1130) { this.appleNumber = 8; } }, },
錨點html代碼:
<div style=" width: 100%;z-index: 2; position: absolute;margin-top: -10px;"> <tab bar-active-color="#10aeff"> <tab-item :selected="1==appleNumber"> <a @click="jump(1)">錨點定位一</a> </tab-item> <tab-item :selected="2==appleNumber"> <a @click="jump(2)">錨點定位二</a> </tab-item> <tab-item :selected="3==appleNumber"> <a @click="jump(3)">錨點定位三</a> </tab-item> <tab-item :selected="4==appleNumber"> <a @click="jump(4)">錨點定位四</a> </tab-item> <tab-item :selected="5==appleNumber"> <a @click="jump(5)">錨點定位五</a> </tab-item> <tab-item :selected="6==appleNumber"> <a @click="jump(6)">錨點定位六</a> </tab-item> <tab-item :selected="7==appleNumber"> <a @click="jump(7)">錨點定位七</a> </tab-item> <tab-item :selected="8==appleNumber"> <a @click="jump(8)">錨點定位八</a> </tab-item> </tab> </div>
划個重點:
1.選取定位坐標
2.監聽頁面滾動,獲取定位坐標相對於屏幕頂部的高度值
3.高亮效果觸發