本文实例为大家分享了vue实现滑动时顶部悬浮固定效果的具体代码,供大家参考,具体内容如下
这个效果是一个项目中抽出来的一个demo效果。
前期准备:
1. 引入jQ
<script src="/UploadFiles/2021-04-02/jquery.js">引入lodash.js
npm install lodash -DfixTop.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>以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月25日
2024年09月25日
- 纯音入心系列纯音乐《天籁古筝》1CD[MP3][331MB]
- 男女对唱典藏天碟《发烧对唱·那个季节里的歌DSD》10CD[WAV]
- 群星2010-歌林精选辑[歌林][WAV+CUE]
- TrioZimbalist-PianoTriosofWeinberg,Auerbach,Dvorak(2024)[24-44,1]wav
- 群星.1992-滚石第一流台湾歌·12王牌大车拼【滚石】【WAV+CUE】
- 林子祥.1984-创作歌集【华纳】【WAV+CUE】
- 周汤豪.2010-周汤豪【华纳】【FLAC分轨】
- Mozart-TheStringQuintets-AmadeusQuartet,CecilAronowitz(2017)[24-44,1][WAV+CUE]
- JamesWilliamsDennisIrwin-Focus(2024,Red)[24-48]FLAC
- 藤泽麻衣《空みあげて》[WAV]
- 纯音入心系列纯音乐《中国古筝经典名曲》1CD[MP3][1.3GB]
- 纯音入心系列纯音乐《古筝新奏:岁月静好与筝语,细水流年与筝同》1CD[MP3][846.9MB]
- 670《脆弱敏感小女生》[320K/MP3][27.53MB]
- 曾琳.2011-好好爱我【南方】【WAV+CUE】
- 范晓萱.1995-RAIN【福茂】【WAV+CUE】