vue滑動(dòng)吸頂及錨點(diǎn)定位的示例代碼
在上篇文章給大家介紹了vue實(shí)現(xiàn)吸頂、錨點(diǎn)和滾動(dòng)高亮按鈕效果 感興趣的朋友可以點(diǎn)擊查看https://www.jb51.net/article/172365.htm
今天給大家繼續(xù)分享vue滑動(dòng)吸頂及錨點(diǎn)定位的代碼,具體內(nèi)容如下所示:
Vue項(xiàng)目中需要實(shí)現(xiàn)滑動(dòng)吸頂以及錨點(diǎn)定位功能。template代碼如下:
<template><div class='main'> <div id=’menu’> <ul> <li v-for='item in tabList' @click=’clickTab’></li> </ul> </div> <div id=’div1’></div> <div id=’div2’></div> <div id=’div3’></div></div> </template>
(1)滑動(dòng)吸頂:
監(jiān)聽scroll事件,獲取頁(yè)面的滾動(dòng)距離,一旦滾動(dòng)距離大于目標(biāo)值,實(shí)現(xiàn)滑動(dòng)吸頂功能。
public isFixed = false;public mounted() { this.menuTop = (document.getElementById(’menu’) as any).offsetTop; window.addEventListener(’scroll’, this.handleScroll); }public handleScroll() { const scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // 獲取滑動(dòng)距離 if (scrollTop < this.menuTop ) { this.isFixed = false; } else { this.isFixed = true; // 設(shè)置fixed定位 } }public destroyed() { window.removeEventListener(’scroll’, this.handleScroll);}
(2)錨點(diǎn)定位。點(diǎn)擊tab,設(shè)置頁(yè)面滾動(dòng)距離。
public clickTab(index: number) { this.activeIndex = index; this.isFixed = true; const menuHeight= (document.getElementById(’menu’) as any).offsetHeight; const div1= (document.getElementById(’div1’) as any).offsetTop; const div2= (document.getElementById(’div2’) as any).offsetTop; const div3= (document.getElementById(’div3’) as any).offsetTop; const div4= (document.getElementById(’div4’) as any).offsetTop; switch (index) { case 0: document.body.scrollTop = document.documentElement.scrollTop = div1 - menuHeight; break; case 1: document.body.scrollTop = document.documentElement.scrollTop = div2 - menuHeight; break; case 2: document.body.scrollTop = document.documentElement.scrollTop = div3 - menuHeight; break; case 3: document.body.scrollTop = document.documentElement.scrollTop = div4 - menuHeight; break; default: document.body.scrollTop = document.documentElement.scrollTop = div1- menuHeight; } }
總結(jié)
到此這篇關(guān)于vue滑動(dòng)吸頂及錨點(diǎn)定位的示例代碼的文章就介紹到這了,更多相關(guān)vue 滑動(dòng)吸頂錨點(diǎn)定位內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. .Net Core和RabbitMQ限制循環(huán)消費(fèi)的方法2. jsp網(wǎng)頁(yè)實(shí)現(xiàn)貪吃蛇小游戲3. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明4. ASP.NET MVC遍歷驗(yàn)證ModelState的錯(cuò)誤信息5. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)6. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向7. asp中response.write("中文")或者js中文亂碼問題8. PHP設(shè)計(jì)模式中工廠模式深入詳解9. CSS hack用法案例詳解10. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法
