由于在网页中顶部导航条占用位置太大,首页的展示效果不完美,所以决定当滚动条向下滚动的时候隐藏滚动条,向上滚动的时候显示滚动条。以达到更玩完美的显示页面内容,避免顶部导航占用页面空间造成页面无法显示完整。
首先下载gsap插件
npm i gsap@^3.12.2
在xxx.vue中引入
import gsap from 'gsap';
import ScrollTrigger from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
在xxx.vue先写好导航条样式,让其固定在页面的对顶部,且脱离文档流。
<div id="proNav" class="pro-nav" v-show="navShow">div>
.pro-nav {
visibility: visible;
z-index: 1000;
position: fixed;
top: 0;
left: 0;
box-sizing: border-box;
width: 100%;
padding: 0 3rem;
height: 4.875rem;
// background-color: #050a09;
background-color: rgba(5, 10, 9, 0);
}
在xxx.vue中
export default {
data() {
return {
navShow: false,
proNavColorTl: gsap.timeline({
reversed: true,
paused: true,
}),
proNavYTl: gsap.timeline({
reversed: true,
paused: true,
}),
}
},
methods: {
initNavAn() {
this.proNavColorTl.to('.pro-nav', {duration: 0.3, backgroundColor: 'rgba(5, 10, 9, .9)', ease: "power3.inOut" });
this.proNavYTl.fromTo(".pro-nav", {yPercent: -100}, { yPercent: 0, duration: 0.45, ease: "power3.inOut",});
this.proNavYTl.play();
},
}
}
@studio-freight/lenis 一个添加滚动阻尼效果的插件
npm i @studio-freight/lenis@^1.0.27
在xxx.vue中使用
// 引入
import Lenis from '@studio-freight/lenis'
//引入lodash
import lodash from "lodash";
export default {
data() {
return {}
},
mounted() {
this.lenisFun();
},
methods: {
lenisFun() {
// 初始化Lenis
const lenis = new Lenis()
function raf(time) {
lenis.raf(time)
requestAnimationFrame(raf)
}
requestAnimationFrame(raf)
Vue.prototype.$lenis = lenis;
let that = this;
// 在scroll事件中做动画
this.$lenis.on('scroll', lodash.throttle(function(e) {
// e.direction 1:向下滚动 0:不滚动 -1:向上滚动
if(e.direction === 1) {
that.proNavYTl.reverse();
} else if(e.direction === -1) {
that.proNavYTl.play();
} else {
that.proNavYTl.play();
}
const vh = document.documentElement.clientHeight;
if(e.targetScroll > vh - 265) {
that.proNavColorTl.play();
} else {
that.proNavColorTl.reverse();
}
}, 500));
},
}
}
这样就实现了导航条根据滚动条的滚动效果显示隐藏,滚动条向下滚动,导航条隐藏,导航条向上滚动,导航条显示。
如果有什么问题,可以留言,有可能代码中有漏掉的部分。