Vue 组件中可以使用滚动事件来监测 position: sticky;
是否已经生效。
首先,在组件的 template 中给要监测的元素添加滚动事件处理函数:
<template>
<div @scroll="handleScroll">
<!-- 要监测的元素 -->
</div>
</template>
然后,在组件的 methods 中定义处理函数:
methods: {handleScroll() {
// 在这里检测 position: sticky; 是否已经生效
}
}
可以使用元素的 getBoundingClientRect 方法来检测元素是否已经生效:
const rect = this.$el.getBoundingClientRect();
if (rect.top <= 0) {
// 元素已经生效
} else {
// 元素未生效
}
注意:需要在处理函数中使用 this.$el
获取元素,因为 getBoundingClientRect
方法需要传入一个 DOM 元素作为参数。