关于前端:项目需要实现按钮悬浮的功能-实现后的记录

5次阅读

共计 1704 个字符,预计需要花费 5 分钟才能阅读完成。

实现可视区域底部悬浮编辑提交等性能的悬浮框:

并当滚动到某处时, 固定在该处

<template>
  <div>
    <slot></slot>
    <div
      v-show="show"
      style="height: 80px"
    ></div>
  </div>
</template>

<script>
import $ from 'jquery'

export default {data () {
    return {
      show: true, // 管制占地位的显示暗藏, 避免抖动
      scoll: null
    }
  },
  mounted () {
    // 插槽传入的组件类名
    const btnDiv = $('.btn_div')
    btnDiv.css({
      'display': 'flex',
      'justify-content': 'center',
      'align-items': 'center',
      'height': '80px',
      'width': '100%',
      'position': 'fixed',
      'z-index': '10000',
      'bottom': '0',
      'left': '50%',
      'transform': 'translateX(-50%)',
      'background-color': '#fff',
      'text-align': 'center',
      'box-shadow': '0 6px 12px rgba(0, 0, 0, 0.9)',
    })

    // 获取可视区域高度
    let clientH = $(window).height()

    this.scoll = () => {
    // '.footer-div' 为页面中须要固定的地位
    // $('.footer-div').offset().top - $(document).scrollTop() 
    // 滚动的间隔与指标地位的差的绝对值小于等于可视区域高度时为悬浮否则固定
      if ((clientH <= ($('.footer-div').offset().top - $(document).scrollTop()))) {
        this.show = true
        btnDiv.css({
          'display': 'flex',
          'justify-content': 'center',
          'align-items': 'center',
          'height': '80px',
          'width': '100%',
          'position': 'fixed',
          'z-index': '10000',
          'bottom': '0',
          'left': '50%',
          'transform': 'translateX(-50%)',
          'background-color': '#fff',
          'text-align': 'center',
          'box-shadow': '0 6px 12px rgba(0, 0, 0, 0.9)',
        })
      } else {
        this.show = false
        btnDiv.css({'position': 'static', 'transform': 'translateX(0%)',
          'box-shadow': '0 0 0 rgba(0, 0, 0, 0.9)',
          'background-color': '#fafafa',
        })
      }
    }
    window.addEventListener('scroll', this.scoll)
  },
  beforeDestroy () {
    // 革除该事件
    window.removeEventListener('scroll', this.scoll)
  },
}
</script>

<style lang="scss" scoped>
// .btn_div {
//   display: flex;
//   width: 100%;
//   justify-content: center;
//   align-items: center;
//   height: 80px;
//   position: fixed;
//   bottom: 0;
//   z-index: 10000;
//   left: 50%;
//   transform: translateX(-50%);
//   // margin: 28px auto;
//   background-color: #fff;
//   text-align: center;
//   box-shadow: 0 6px 12px rgba(0, 0, 0, 0.9);
// }
</style>
正文完
 0