当前位置: 移动技术网 > IT编程>开发语言>JavaScript > vue实现固定位置显示功能

vue实现固定位置显示功能

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

在vue项目中实现吸顶效果.

比如说,我们要实现的功能是导航栏在页面下滑到一定位置之后,便固定不定。

首先:要在mounted生命周期内监听'scroll'事件,事件触发后,执行一个处理滚动的函数。

window.addeventlistener('scroll', this.handlescroll)
  methods:{
handlescroll () {
 var scrolltop = window.pageyoffset || document.documentelement.scrolltop || document.body.scrolltop
 var offsettop = document.queryselector('#searchbar').offsettop
 if (scrolltop > offsettop) {  //判断是否到达了顶部
  this.searchbarfixed = true
 } else {
  this.searchbarfixed = false
 }
}
 }

完整源代码如下:

<template>
<div>
 <div class="nav"></div>
<div class="searchbar" id="searchbar">
 <ul :class="searchbarfixed == true ? 'isfixed' :''"> //用v-bind绑定样式
  <li>区域<i class="iconfont icon-jiantouxia"></i></li>
  <li>价格<i class="iconfont icon-jiantouxia"></i></li>
  <li>房型<i class="iconfont icon-jiantouxia"></i></li>
  <li>更多<i class="iconfont icon-jiantouxia"></i></li>
 </ul>
</div>
<div class="content">
</div>
</div>
</template>
<script>
 export default {
  components:{
  },
mounted () {
 window.addeventlistener('scroll', this.handlescroll)
},
    data(){
     return {
      searchbarfixed:false
    } 
 },
  methods:{
handlescroll () {
 var scrolltop = window.pageyoffset || document.documentelement.scrolltop || document.body.scrolltop
 var offsettop = document.queryselector('#searchbar').offsettop
 if (scrolltop > offsettop) {
  this.searchbarfixed = true
 } else {
  this.searchbarfixed = false
 }
},
 }
 }
</script>
<style lang="less" scope>
.nav{
 height: 250px;
}
.content{
 height: 1900px;
}
.searchbar{
 .isfixed{
  position:fixed;
  background-color:#fff;
  top:0;
  z-index:999;
 }
 ul {
  width:100%;
  height: 40px;
  line-height: 40px;
  display: flex;
  li {
   list-style: none;
   font-size: 0.8rem;
   text-align: center;
   flex: 1;
   i {
    font-size: 0.9rem;
    padding-left: 5px;
    color: #ccc;
   }
  }
  border-bottom: 1px solid #ddd;
 }
}
</style>

总结

以上所述是小编给大家介绍的vue实现固定位置显示功能,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网