vue3 div移动超出滚动条位置 滚动条位置也移动
要实现这个效果,你可以使用Vue的ref和watch来监听div的位置变化,并根据变化来更新滚动条的位置。
首先,在Vue的setup函数中,使用ref来定义一个变量来保存div的位置信息:
import { ref, onMounted } from 'vue';
export default {
setup() {
const divRef = ref(null);
const scrollRef = ref(null);
onMounted(() => {
// 获取div的位置信息
const div = divRef.value;
const scroll = scrollRef.value;
// 监听div的位置变化
const observer = new IntersectionObserver(entries => {
const entry = entries[0];
const { x, y } = entry.boundingClientRect;
// 更新滚动条的位置
scroll.scrollTo(x, y);
});
observer.observe(div);
});
return {
divRef,
scrollRef,
};
},
};
然后,在模板中,将div和滚动条绑定到对应的ref上:
<template>
<div ref="scrollRef" style="overflow: scroll; height: 200px;">
<div ref="divRef" style="width: 1000px; height: 1000px;"></div>
</div>
</template>
这样,当div的位置变化时,滚动条的位置也会相应地更新
原文地址: https://www.cveoy.top/t/topic/iyhf 著作权归作者所有。请勿转载和采集!