方式一:直接给滚动的部分加个 @scroll="handleScroll" 然后js里面进行业务处理
<div class="tip-info" @scroll="handleScroll">
<div class="tip-blank" :key="outerIndex" v-for="(item, outerIndex) in htmlCaption">
</div>
methods: {
// 滚动事件
handleScroll(event) {
const dialog = event.target;
if (dialog.scrollHeight - dialog.scrollTop === dialog.clientHeight) {
// 当内容滑动到底部时,执行想要的操作
}
}
}
方式二:可以采用给滚动内容,在最后一个内容的div后面追加一个新的元素,然后IntersectionObserver 进行观察
<div class="tip-info">
<div class="tip-blank" :key="outerIndex" v-for="(item, outerIndex) in htmlCaption">
</div>
mounted() {
this.addNewElementToTipBlank();
},
methods: {
addNewElementToTipBlank() {
// 创建新元素
const newElement = document.createElement('div');
newElement.className = 'tip-box';
newElement.textContent = 'New Tip Box Added';
// 找到 tip-blank 类所在的 div 元素
const tipBlankDivs = document.querySelectorAll('.tip-blank');
const lastTipBlankDiv = tipBlankDivs[tipBlankDivs.length - 1]; // 获取最后一个 tip-blank 元素
// 在最后一个 tip-blank 元素后面插入新的 div 元素
if (lastTipBlankDiv) {
lastTipBlankDiv.insertAdjacentElement('afterend', newElement);
}
// 创建一个观察者实例
const observer = new IntersectionObserver((entries) => {
console.log(entries);
entries.forEach((entry) => {
// entry.isIntersecting 判断目标元素是否在视口中
if (entry.isIntersecting) {
console.log('目标元素在视口中!');
}
else {
console.log('目标元素不在视口中.');
}
});
});
// 开始观察某个元素
const targetElement = document.querySelector('.tip-box');
if (targetElement) {
observer.observe(targetElement);
}
// 停止观察
// 如果你不再需要观察某个元素,你可以调用:
observer.unobserve(targetElement);
// 如果你想停止观察所有元素,你可以调用:
observer.disconnect();
},
}
IntersectionObserver具体的用法可以参考 https://www.cnblogs.com/anans/p/17697522.html
方式三 如果前2种方式不可行,可试试这一种
<template>
<div class="tip-info" @scroll.passive="handleScroll">
<div class="sn-f-c-c tip-blank" :key="i" v-for="(item, i) in caption">
{{item}}
</div>
</div>
</template>
<script>
data() {
return {
caption: []
};
},
methods: {
// 接口返回数据
interface() {
this.caption = ''; // 接口返回数据
if (this.caption.length > 0) {
this.$nextTick(() => {
this.handleScroll({
target: document.querySelector('.tip-info')
});
});
}
},
handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target;
// 条件判断(scrollHeight - (scrollTop + clientHeight)) / clientHeight <= 0.05
// 是在计算滚动条距离底部的距离与可视区域高度的比例。如果这个比例小于或等于5%(0.05),则认为滚动条已经非常接近底部。
if ((scrollHeight - (scrollTop + clientHeight)) / clientHeight <= 0.05) {
console.log('内容到底了');
}
}
}
</script>