回到顶部 回到底部

1.按钮的样式

<div class="fixed flex flex-col space-y-3 text-white right-72 bottom-24">
      <button
        class="p-5 w-20 h-20 tracking-widest flex items-center justify-center bg-center text-white bg-[rgba(62,61,67,1.00)] rounded hover:bg-blue-700"
        @click="scrollToBottom">
        <img class="w-20 h-20" src="@/assets/button/post.svg" />
      </button>
      <button
        class="p-5 w-20 h-20 tracking-widest flex items-center justify-center text-white bg-[rgba(62,61,67,1.00)] rounded hover:bg-blue-700"
        @click="queryTopicByCourseId">
        <img class="w-20 h-20" src="@/assets/button/refresh.svg" />
      </button>
      <button
        class="p-6 w-20 h-20 tracking-widest flex items-center justify-center text-white bg-[rgba(62,61,67,1.00)] rounded hover:bg-blue-700"
        @click="scrollToTop">
        <img class="w-20 h-20" src="@/assets/button/backTop.svg" />
      </button>
    </div>

2.包裹内容

<div ref="scrollContainer" style="overflow-y: scroll">
内容
</ div>

3.代码

const scrollContainer = ref(null)

const setupScrollEvents = () => {
  scrollContainer.value.addEventListener('scroll', handleScroll)
}

const removeScrollEvents = () => {
  scrollContainer.value.removeEventListener('scroll', handleScroll)
}

const handleScroll = () => {
  const scrollHeight = scrollContainer.value.scrollHeight - scrollContainer.value.clientHeight;
  const scrollTop = scrollContainer.value.scrollTop
  const scrollPercentage = (scrollTop / scrollHeight) * 100

  // 当滚动百分比高于 80% 时显示回到顶部按钮,否则隐藏
  if (scrollPercentage > 80) {
    // 显示回到顶部按钮
  } else {
    // 隐藏回到顶部按钮
  }
}

const scrollToTop = () => {
  scrollContainer.value.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
}

const scrollToBottom = () => {
  const scrollHeight = scrollContainer.value.scrollHeight - scrollContainer.value.clientHeight;
  scrollContainer.value.scrollTo({
    top: scrollHeight,
    behavior: 'smooth'
  })
}

onUnmounted(removeScrollEvents)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值