程序员必懂小知识之组件吸顶实现

882 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

前言

  • 大家好,我是_Peach,今天来聊下工作中常用的'吸顶效果'实现

什么是吸顶效果

滚动到一定的高度 会吸附到顶部不动

  • 滚动前

image.png

  • 滚动后

image.png

怎么实现吸顶效果

  1. 通过window.addEventListener("scroll", this.initHeight);事件监听滚动
  2. 根据高度判断是否添加类名
  3. 这里用到了vue的知识点 v-bind 语法糖: :class="{'is_fixed': isfixed}"
  4. 通过变量的方式来控制类名
  5. 离开该页面时通过vue的生命周期中的destroyed()实例销毁后滚动事件

代码实现

html结构

<div class="index">
    <div class="navHeader">
      <div class="container"><h1>我是头部</h1></div>
    </div>
    <div class="top" :class="{ is_Fixed: isFixed }">
      <div class="container"><h2>吸顶功能实现</h2></div>
    </div>
    <div class="wrapper">
      <div class="container">
        <p>内容</p>
        <p>内容</p>
        <p>内容</p>
        <p>内容</p>
        <p>内容</p>
        <p>内容</p>
      </div>
    </div>
  </div>

js实现

export default {
  name: 'index',
  data() {
    return {
      isFixed: false
    }
  },
  mounted() {
    window.addEventListener('scroll', this.initHeight)
  },
  methods: {
    initHeight() {
      let scrollTop =document.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop //获取页面高度
      this.isFixed = scrollTop > 80 ? true : false //控制类名是否显示
    }
  },
  destroyed() {
    window.removeEventListener('scroll', this.initHeight) //销毁是清除scroll事件
  }
}

css样式

<style lang="less">
*{
  padding: 0;
  margin: 0;
}
.home {
  height: 500px;
  .navHeader {
    height: 80px;
    padding-top: 10px;
    text-align: center;
    color: #0009;
    background: #ccc;
  }
  .top {
    height: 60px;
    text-align: center;
    font-size: 18px;
    font-weight: bold;
    line-height: 60px;
    color: #fff;
    background: #f60;
    &.is_Fixed {
      position: fixed;
      top: 0;
      width: 100%;
    }
  }
  p {
    height: 150px;
    margin: 10px 0;
  }
}
.container {
  width: 1226px;
  margin-left: auto;
  margin-right: auto;
}
</style>

总结

今天的分享先到这里,大家好好努力吧