html将按钮固定到页面底部,滑动到底部时消失

需求:一个比较长的页面,其操作按钮在最底部,每次要操作按钮都要把滚动条下拉。想将按钮固定在页面的下方,滚动到底部的时候这个按钮消失。

功能实现如图:

 

    <!-- foot -->
    <div class="foot" v-if="backTopShow">
      <div class="next-btn">
        <el-button @click="onRegisterClick">登录</el-button>
      </div>
    </div>
.foot {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 999;
  height: 60px;
  line-height: 60px;
  background-color: white;
  box-shadow: 0 -2px 10px $C25;

  .next-btn {
    margin-bottom: 20px;
    text-align: center;
  }
}
const backTopShow = ref(true);

// scrollTop: 滚动条滚动距离
// clientHeight: 窗口可视范围高度
// scrollHeight: 元素实际高度,包括溢出的部分
const handleScroll = (e: any): void => {
  const element = e.target;
  const bottomOffset = 100;    // 当到达离底部100的时候就不再显示
  if (element.scrollTop + element.clientHeight + bottomOffset >= element.scrollHeight) {
    backTopShow.value = false;
  } else {
    backTopShow.value = true;
  }
};

// 页面的滚动条是在app元素上的,所以要获取app的dom元素
onMounted(() => {
  const ele = document.getElementById('app');
  ele?.addEventListener('scroll', handleScroll);
});

参考资料:

scrollHeight,clientHeight,scrollTop明晰 - 简书 (jianshu.com)

猜你喜欢

转载自blog.csdn.net/weixin_43961652/article/details/129840591