vue+jquery+lodash實現(xiàn)滑動時頂部懸浮固定效果
本文實例為大家分享了vue實現(xiàn)滑動時頂部懸浮固定效果的具體代碼,供大家參考,具體內(nèi)容如下
這個效果是一個項目中抽出來的一個demo效果。

前期準備:
1. 引入jQ
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
引入lodash.js
npm install lodash -D
fixTop.vue組件的
<template>
<div class="fixtop2">
<header class="header" ref="header"></header>
<div class="nav" ref="nav" :class="{isFixed:isFixed}">
<div class="box" v-for="(item,index) in list" :key="index">
{{item.title}}
</div>
</div>
<ul class="content">
<li v-for="(item,index) in new Array(20)" :key="index">{{index+1}}</li>
</ul>
</div>
</template>
<script>
var throttle = require('lodash/throttle'); //從lodash中引入的throttle節(jié)流函數(shù)
export default {
name: 'navScroll2',
data() {
return {
list: [
{ title: 'AAAA', id: 1 },
{ title: 'BBBB', id: 2 },
{ title: 'CCCC', id: 3 },
{ title: 'DDDD', id: 4 },
],
isFixed: false, //是否固定的
throttleScroll: null, //定義一個截流函數(shù)的變量
};
},
methods: {
//滾動的函數(shù)
handleScroll() {
let h = $(this.$refs.header).outerHeight(); //header的高度
let wh = $(window).scrollTop(); //滾動的距離的,為什么這里使用的jq,因為不用考慮的什么的兼容問題
let navH = $(this.$refs.nav).outerHeight(); //nav的高度
if (wh > h) {
this.isFixed = true;
} else {
this.isFixed = false;
}
},
},
mounted() {
//寫在掉接口的里面的
this.$nextTick(() => {
//這里使用監(jiān)聽的scroll的事件,為什么要使用的節(jié)流函數(shù),如果不使用的,頁面一直在滾動計算的,這樣在
//使用手機時候,出現(xiàn)非??ǖ?,隔一段時間計算,大大降低了性能的消耗(具體的好處自己去查資料)
window.addEventListener('scroll', this.throttleScroll, false);
});
this.throttleScroll = throttle(this.handleScroll, 100);
},
deactivated() {
//離開頁面需要remove這個監(jiān)聽器,不然還是卡到爆。
window.removeEventListener('scroll', this.throttleScroll);
},
};
</script>
<style lang="scss" scoped>
.fixtop2 {
min-height: 100vh;
}
.header {
height: 5rem;
width: 100%;
background-color: red;
}
.nav {
display: flex;
width: 100%;
background-color: pink;
&.isFixed {
position: fixed;
left: 0;
top: 0;
z-index: 9999;
}
.box {
font-size: 0.3rem;
padding: 0 0.3rem;
height: 0.9rem;
line-height: 0.9rem;
color: #333333;
flex: 1;
}
}
.content {
height: 20rem;
li {
width: 100%;
height: 1rem;
border-bottom: 1px solid #000;
}
}
</style>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于vue.js組件數(shù)據(jù)流的問題
本篇文章主要介紹了關(guān)于vue.js組件數(shù)據(jù)流的問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07
Vue純前端使用exceljs導(dǎo)出excel文件的完整圖文教程
這篇文章將一步一步為大家詳細介紹一下exceljs插件中的使用,以及如何使用exceljs導(dǎo)出excel文件,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-03-03
使用axios發(fā)送post請求,將JSON數(shù)據(jù)改為form類型的示例
今天小編就為大家分享一篇使用axios發(fā)送post請求,將JSON數(shù)據(jù)改為form類型的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10
在vue和element-ui的table中實現(xiàn)分頁復(fù)選功能
這篇文章主要介紹了在vue和element-ui的table中實現(xiàn)分頁復(fù)選功能,本文代碼結(jié)合圖文的形式給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12
vue-router鉤子函數(shù)實現(xiàn)路由守衛(wèi)
這篇文章主要介紹了vue-router鉤子函數(shù)實現(xiàn)路由守衛(wèi),對vue感興趣的同學(xué),可以參考下2021-04-04
解決Vue中的生命周期beforeDestory不觸發(fā)的問題
這篇文章主要介紹了解決Vue中的生命周期beforeDestory不觸發(fā)的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07

