元素至顶

63 阅读1分钟

html

<div :class="isFixed? 'isFixed' : ''" ref="btn">
      <div class="button">
         <el-button type="primary" @click="onQuery">取货码查询</el-button>
         <el-button type="primary" @click="onWriteOff">取货码核销</el-button>
      </div>
 </div>

css

 .isFixed {
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  z-index: 1000;
  background: #ffffff;
  padding: 10px 20px;
}

js

import { onUnmounted, onMounted, ref } from 'vue'
let isFixed = ref<boolean>(false)
const btn = ref()
    let handleScroll =()=>{
      var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; // 滚动条到顶部距离
            var Top = btn.value.getBoundingClientRect().top // 元素到顶部距离
      if(Top<50){
        isFixed.value = true
      }else if(scrollTop == 0){
        isFixed.value = false
      }
    }
    onMounted(()=>{
      window.addEventListener('scroll', handleScroll);
    })
    onUnmounted (()=>{
      window.removeEventListener('scroll', handleScroll)
    })