scrollTop给父级的有滚动条的元素设置,而不是给目标元素设置
话不多说 直接上代码(方法可以直接复制拿去, html部分需要改成你的元素的ref和点击回到顶部的方法名称)
html
<section ref="scrollbox" class="inner-body">
<div>
这里放了很多内容 出现了滚动条
</div>
</section>
<button @click="gotop">点击置顶</button>
mounted() {
//开启监听滚动条事件
this.listenerFunction();
},
beforeDestroy(){
//移除滚动条事件
this.beforeDestroy()
},
methods: {
listenerFunction(e) {
document.addEventListener("scroll", this.handleScroll, true);
},
beforeDestroy() {
document.removeEventListener("scroll", this.listenerFunction);
},
//监听滚动事件
handleScroll (e) {
// var st = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
// console.log(st)
//1.一般情况下直接打印上处注释掉的代码就可以看到滚动条距离顶部的距离
//2.但如果发现一直是0 可能是因为overflow设置导致获取出错
//3.此时打印事件函数e 和 e.target.scrollTop 可以得到距离顶部的距离
// console.log(e);
console.log(e.target.scrollTop);
//4.但是我们一般可能是点击某处按钮 使其滚动条置顶 那么我们获取的事件event是点击的那个按钮
//而不是对应的滚动条了 此时需要用到ref
//注意一定要找到滚动条所在的那个元素(可以通过控制台摸到滚动条的那个元素) 给其设置ref
//再次打印 此时发现e.target===this.$refs.scrollbox
// console.log(e.target===this.$refs.scrollbox);
console.log(this.$refs.scrollbox.scrollTop);
},
//5.点击回到顶部
gotop(){
this.$refs.scrollbox.scrollTop = 0
}
}
注意最重要的一点:ref一定要设置在滚动条的那个元素上