Requirement: On a relatively long page, the operation button is at the bottom, and the scroll bar must be pulled down every time the button is to be operated. I want to fix the button at the bottom of the page, and the button disappears when scrolling to the bottom.
The function is realized as shown in the figure:
<!-- 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);
});
References:
scrollHeight, clientHeight, scrollTop are clear - Short Book (jianshu.com)