在这个例子中,我们使用 ref 属性来获取 info 元素的引用,并在 mounted 钩子中使用 window.addEventListener 来监听滚动事件。在滚动事件处理函数 handleScroll 中,我们计算滚动条的位置,并将其与可视区高度进行比较。如果滚动条位置大于可视区高度,我们将滚动条位置重置为可视区高度,从而使元素始终保持在可视区中。
示例代码
template>
<div>
<div class="info" ref="infoRef">
<!-- 你的内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
scrollTop: 0,
};
},
mounted() {
window.addEventListener("scroll", this.handleScroll);
},
beforeDestroy() {
window.removeEventListener("scroll", this.handleScroll);
},
methods: {
handleScroll() {
this.scrollTop = window.scrollY;
if (this.scrollTop > this.$refs.infoRef.offsetHeight) {
// 当滚动条位置大于可视区高度时,将滚动条位置重置为可视区高度
this.scrollTop = this.$refs.infoRef.offsetHeight;
}
},
},
};
</script>