先看效果
介紹
一個簡單的靜態頁面主要是使用 better-scroll 做橫向滾動,
點擊標籤滾動到相應位置,以及滾到相應位置後對應標籤顯示紅色。
開發過程中遇到了幾個問題
一:初始化的時候要計算內容的高度,一直有誤差,因爲一開始直接用img引入的,沒加載完就計算高度就會有問題
解決辦法:用background寫圖片,然後高度寫死
二:滾動到某個內容,對應標籤高亮
這裏比較的是當前滾動位置高度和內容距離dom頂部的高度加上實際nav的高度
三:better-scroll fixed後滾動失效
這裏是因爲沒有給固定的寬度,用了100%造成的。這裏給了tab-warp 寬度就解決了
記錄一下和大家共同學習
主要代碼
因爲是靜態野蠻標題放到數組中了
itemList: [{
'title': '戰略升級'
},
{
'title': '官方授權'
},
{
'title': '100%正品'
},
{
'title': '全鏈路監管'
},
{
'title': '陽光保險'
},
{
'title': '售後無憂'
},
{
'title': '專業倉儲'
},
{
'title': '用戶好評'
},
{
'title': '媒體監督'
},
{
'title': '資質公示'
}
],
mounted() {
this.$nextTick(() => {
window.addEventListener('scroll', this.handleScroll) // 監聽滾動事件
this.InitTabScroll() // 初始化滾動
})
},
methods: {
handleChange(index) {
this.swipeIndex.nowIndex = index + 1
},
// 監聽滾動事件
handleScroll() {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop ||
document.body.scrollTop
// 吸頂效果
const isFixed = scrollTop >= this.tabToTop
if (isFixed !== this.isFixed) {
this.isFixed = isFixed
}
// 當頁面滾動時候標籤也要滾動
for (var i = 0; i < this.contentH.length; i++) {
// 循環判斷內容高度的數組,滾動的高度小於前一個大於後一個設置,這裏是包含下拉麪板的高度(我也不知道爲什麼,自己試出來的,尷尬)
if (scrollTop + this.tabRealHeight> this.contentH[i] && scrollTop + this.tabRealHeight< this.contentH[i + 1]) {
if (this.checkIndex !== i) {
this.checkIndex = i
// 然後設置標籤高亮,滾動到居中位置
this.scroll.scrollToElement(this.$refs.tabitem[i], 300, -100)
}
}
}
},
// 初始化方法
InitTabScroll() {
/*
* 這裏有幾個高度需要注意一下,因爲後面要計算滾動距離,這裏要很精確要不就會出問題
* tabToTop tab距離頂部的高度,也就是第一個圖片的高度
* tabRealHeight 是tab點下拉箭頭顯示面板後的高度
* tabHeight 就是tab的高度了
*/
// 頭部高度
this.tabToTop = this.$refs['tab-containter'].offsetTop
// tab 帶面板高度
this.tabRealHeight = this.$refs['tab-containter'].offsetHeight
// tab 高度
this.tabHeight = this.$refs['tabitem'][0].offsetHeight
// 內容高度要記錄下來放在數組裏,當頁面滾動的時候判斷在哪個區間,對於標籤高亮
for (let i = 0; i < 11; i++) {
this.contentH.push(this.$refs['contentItem' + i].offsetTop)
}
// nav橫向滾動寬度,然後設置
let width = 0
for (let i = 0; i < this.itemList.length; i++) {
width += this.$refs.tabitem[i].getBoundingClientRect().width // getBoundingClientRect() 返回元素的大小及其相對於視口的位置
}
this.$refs.tabWrapper.style.width = width + 'px'
this.$nextTick(() => {
if (!this.scroll) {
this.scroll = new BScroll(this.$refs.tab, {
startX: 0,
click: true,
scrollX: true,
scrollY: false,
eventPassthrough: 'vertical'
})
} else {
this.scroll.refresh()
}
})
},
// 點擊nav標籤
checkStatus(index, pop) {
this.checkIndex = index
// 點擊展開面板的選項
if (pop) {
this.flag = !this.flag
}
// 點擊標籤後,標籤要滾到nav中間位置
this.scroll.scrollToElement(this.$refs.tabitem[index], 300, -100)
// 獲取該點擊標籤對應的內容區域,距離dom頂部高度
const offsetTop = this.$refs['contentItem' + index].offsetTop
// 頁面滾動到高度減去nav的位置
window.scrollTo(0, offsetTop - this.tabHeight)
}
}
總結
主要功能實現了,但是還有很多需要優化的地方
查看demo 正品保障 完整代碼 github
微信掃碼看我們的小程序
關於我
您可以掃描添加下方的微信並備註 Soul 加交流羣,給我提意見,交流學習。