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)