VUE实现滚动监听导航栏置顶的方法
HTML
专注于为中小企业提供成都做网站、成都网站建设服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业兖州免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了超过千家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
非重点的代码,比如样式啥的,我就不放上来了,一笔带过
简略的写一下html代码,可以对照文章最后的效果图看,应该不难理解
资源信息
VUE
1. data ()
data () {
paddingBottom: '1.5rem', // 给最外层div一个padding-bottom
// 因为footer是fixed定位 如果padding-bottom为0 数据列表拉到最下面的时候 会有部分数据被footer挡住
isFixed: false, // bar浮动
offsetTop: 0, // 触发bar浮动的阈值
marginTop: 0, // 触发bar浮动的同时 给数据列表一个margin-top 防止列表突然上移 会很突兀
advertShow: true, // 广告显示
}
2. mounted ()
mounted () {
// 设置初始的 padding-bottom 值为 footer 的高度 +20 防止数据列表拉到最下面被footer挡住 +多少自定
this.paddingBottom = document.querySelector('.footer').offsetHeight + 20 + 'px';
// 设置bar浮动阈值为 #fixedBar 至页面顶部的距离
this.offsetTop = document.querySelector('#fixedBar').offsetTop;
// 开启滚动监听
window.addEventListener('scroll', this.handleScroll);
}
3. methods
methods: {
// 关闭广告
del () {
this.advertShow = true;
this.$nextTick(() => {
this.paddingBottom = document.querySelector('.footer').offsetHeight + 20 + 'px';
});
},
// 滚动监听 滚动触发的效果写在这里
handleScroll () {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop >= this.offsetTop) {
this.isFixed = true;
this.marginTop = document.querySelector('#fixedBar').offsetHeight + 'px';
} else {
this.isFixed = false;
this.marginTop = 0;
}
}
}
4. destroyed ()
destroyed () {
window.removeEventListener('scroll', this.handleScroll); // 离开页面 关闭监听 不然会报错
}效果图




以上这篇VUE 实现滚动监听 导航栏置顶的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持创新互联。
分享文章:VUE实现滚动监听导航栏置顶的方法
转载源于:http://www.jxjierui.cn/article/pjhgeg.html


咨询
建站咨询
