如何在滚动到页面底部时隐藏 div?
<div id="cookieID">
<p class="cookie-policy">{{ cookiePolicy }}</p>
</div>
答案 0 :(得分:1)
试试这个:
<template>
<div>
<p v-if="!scrolledToBottom" class="cookie-policy">{{ cookiePolicy }}</p>
</div>
</template>
<script>
export default {
data: () => ({
scrolledToBottom: false,
}),
mounted() {
this.scroll()
},
methods: {
scroll() {
window.onscroll = () => {
const bottomOfWindow =
Math.max(
window.pageYOffset,
document.documentElement.scrollTop,
document.body.scrollTop
) +
window.innerHeight ===
document.documentElement.offsetHeight
if (bottomOfWindow) {
this.scrolledToBottom = true
}
}
},
},
}
</script>
根据您的用例,您可能更喜欢使用 v-if
而不是 v-show
。
答案 1 :(得分:0)
data() {
return {
hasScrolledBottom: false,
};
},
mounted(){
window.addEventListener('scroll', this.onScroll, true);
},
beforeDestroy() {
window.removeEventListener('scroll', this.onScroll, true);
},
methods: {
onScroll(){
var element = e.target;
if (element.scrollHeight - element.scrollTop === element.clientHeight){
console.log('bottom scrolled');
this.hasScrolledBottom = true;
} else {
console.log('Im not in bottom scrolled');
this.hasScrolledBottom = false;
}
您可以使用变量 hasScrolledBottom
来隐藏 div:
<div id="cookieID" v-if="hasScrolledBottom">
<p class="cookie-policy">{{ cookiePolicy }}</p>
</div>
仅供参考,scrollHeight
在浏览器中得到广泛支持,更准确地说是 ie 8,而 clientHeight
和 scrollTop
都被所有人支持。即使 ie 6。这应该是跨浏览器安全的。