当前位置: 移动技术网 > IT编程>脚本编程>vue.js > VUE 实现滚动监听 导航栏置顶的方法

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

2019年06月03日  | 移动技术网IT编程  | 我要评论

伟梦清水湾,潜龙夺宝,外科医生奉达熙国语

html

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

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

<div :style="{ paddingbottom: paddingbottom}">

 <header>资源信息</header>

 <div>
  <!-- 公司信息 浏览量 -->
 </div>

 <div id="fixedbar" :class="{ fixedbar: isfixed }">
  <!-- 品名 -->
  <!-- 规格 -->
  <!-- 产地 -->
  <!-- 单价 -->
 </div>

 <div :style="{ margintop: margintop }">
  <!-- 数据列表 -->
 </div>

 <footer class="footer">
  <button>订阅</button>
  <button>关闭</button>
  <div v-show="advertshow">
   <a @click="del">×</a>
   <img src="./广告.jpg" />
  </div>
 </footer>

</div>

<style>
 .fixedbar {
  position: fixed;
  top: 0;
  z-index: 999;
  width: 100%;
 }
</style>

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网