Vue中监听某个元素滚动盒子中滚动条的位置
监听某个元素滚动盒子中滚动条的位置
·
监听某个元素滚动盒子中滚动条的位置
代码:
<template>
<!-- 按照上面代码自己写一个就好了 -->
</template>
<script>
export default {
mounted () {
// 获取指定元素
const scrollview = this.$refs['scrollview'];
// 添加滚动监听,该滚动监听了拖拽滚动条
// 尾部的 true 最好加上,我这边测试没加 true ,拖拽滚动条无法监听到滚动,加上则可以监听到拖拽滚动条滚动回调
scrollview.addEventListener('scroll', this.scrollChange, true);
},
// beforeDestroy 与 destroyed 里面移除都行
beforeDestroy () {
// 获取指定元素
const scrollview = this.$refs['scrollview'];
// 移除监听
scrollview.removeEventListener('scroll', this.scrollChange, true);
},
methods: {
// 滚动监听
scrollChange (e) {
console.log('父滚动条到页面顶部距离', e.target.offsetTop)
console.log('相对距离', this.$refs.scrollview.scrollTop)
console.log('绝对距离', e.target.offsetTop + this.$refs.scrollview.scrollTop)
},
}
}
</script>
希望文档能帮助到您,最后求个赞,谢谢~
更多推荐
已为社区贡献5条内容
所有评论(0)