栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

VUE 实现滚动监听 导航栏置顶的方法

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

VUE 实现滚动监听 导航栏置顶的方法

HTML

非重点的代码,比如样式啥的,我就不放上来了,一笔带过

简略的写一下html代码,可以对照文章最后的效果图看,应该不难理解



 
资源信息
×
.fixedBar { position: fixed; top: 0; z-index: 999; width: 100%; }

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 实现滚动监听 导航栏置顶的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/79246.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号