您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章给大家分享的是有关vue+jquery+lodash如何实现滑动时顶部悬浮固定效果的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
这个效果是一个项目中抽出来的一个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节流函数 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>
感谢各位的阅读!关于“vue+jquery+lodash如何实现滑动时顶部悬浮固定效果”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。