1. 程式人生 > >vue+jquery+lodash 實現的滑動時頂部懸浮固定

vue+jquery+lodash 實現的滑動時頂部懸浮固定

這個效果是一個專案中抽出來的一個demo效果。
這裡寫圖片描述
前期準備:
1. 引入jQ

  <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
  1. 引入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節流函式 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, //定義一個截流函式的變數 }; }, methods: { //滾動的函式 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(() => { //這裡使用監聽的scroll的事件,為什麼要使用的節流函式,如果不使用的,頁面一直在滾動計算的,這樣在 //使用手機時候,出現非常卡的,隔一段時間計算,大大降低了效能的消耗(具體的好處自己去查資料) window.addEventListener('scroll', this.throttleScroll, false); }); this.throttleScroll = throttle(this.handleScroll, 100); }, deactivated() { //離開頁面需要remove這個監聽器,不然還是卡到爆。 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>