使用vue封装固钉Affix组件,滚动条到底部时自动吸附,离开底部时自动相对窗口固定

<template>
  <div class="back-btn-position-fx-style"><button class="back-btn-style"
            @click="$router.go(-1)">返回</button></div>
</template>

<script>
export default {
  name: 'Affix',
  props: {
  },
  data () {
    return {
    }
  },
  mounted () {
    window.addEventListener('scroll', this.handleScroll)
  },
  methods: {
    handleScroll (e) {
      if (document.documentElement.scrollHeight - document.documentElement.scrollTop <= document.documentElement.clientHeight + 317) {
        let fxDom = document.getElementsByClassName('back-btn-position-fx-style')
        if (fxDom.length > 0) {
          fxDom[0].classList.add('back-btn-position-ab-style')
          fxDom[0].classList.remove('back-btn-position-fx-style')
        }
      } else {
        let adDom = document.getElementsByClassName('back-btn-position-ab-style')
        if (adDom.length > 0) {
          adDom[0].classList.add('back-btn-position-fx-style')
          adDom[0].classList.remove('back-btn-position-ab-style')
        }
      }
    }
  }
}
</script>

<style scoped lang="less">
.back-btn-position-ab-style {
  position: absolute;
  bottom: 20px;
  margin-left: 1074px;
}
.back-btn-position-fx-style {
  position: fixed;
  bottom: 20px;
  margin-left: 1074px;
}
</style>

封装时我写的这个项目底部高度是317像素,可根据自己业务需求把代码中的317改成相应的底部高度

    原文作者:弱鸡的前端程序员
    原文地址: https://segmentfault.com/a/1190000019863589
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞