<!-- 返回顶部按钮示例 -->
<template>
<div>
<div
ref="scrollContainer"
style="overflow-y: auto; height: 200px; position: relative;"
@scroll="checkScroll"
>
<!-- 这里是长内容 -->
<p v-for="i in 100" :key="i">这是第 {{ i }} 行内容</p>
</div>
<button v-if="showButton" @click="scrollToTop" style="position: absolute; bottom: 10px;">
回到顶部
</button>
</div>
</template>
<script>
export default {
data() {
return {
showButton: false,
scrollThreshold: 100 // 滚动阈值
};
},
methods: {
checkScroll() {
const scrollTop = this.$refs.scrollContainer.scrollTop;
this.showButton = scrollTop > this.scrollThreshold;
},
scrollToTop() {
this.$refs.scrollContainer.scrollTop = 0;
}
},
mounted() {
// 初始化时调用一次,确保按钮的初始状态
this.checkScroll();
}
};
</script>
<style scoped>
/* 添加一些样式使按钮更好看 */
button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
right: 10px; /* 距离右边10px */
bottom: 10px; /* 距离底部10px */
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
</style>
展示效果如下图:
点击按钮后,回到顶部