代码
<template>
<div class="test">
<div ref="box" class="box" style="height:400px;overflow:hidden">
<ul class="content">
<li class="green"></li>
<li class="yellow"></li>
<li class="red" ref="red"></li>
<li class="blue"></li>
</ul>
</div>
<button @click="goRed">跳转到红色</button>
</div>
</template>
<script>
import BScroll from "better-scroll";
export default {
created() {
this.$nextTick(() => {
// 使用$nextTick 等待DOM更新后再做下面操作
this.initScroll();
});
},
methods: {
initScroll() {
console.log(this.$refs.box); //没有东西输出说明还未获取到dom,需要先获取到dom
//创建BScroll实例
this.Scroll = new BScroll(this.$refs.box, {
click: true,
probeType: 3 //设置3可以实时派发scroll事件
});
//注册滑动事件,同时需要设置probeType派发scroll事件
this.Scroll.on("scroll", pos => {
console.log(pos.y); //获取滑动到的y值
});
},
goRed(){
this.Scroll.scrollToElement(this.$refs.red,2000) //参数1:将要跳转到的dom,参数2:滑动到该dom的时间
}
},
};
</script>
<style scoped>
ul li {
width: 100%;
height: 300px;
}
.green {
background: green;
}
.yellow {
background: yellow;
}
.red {
background: red;
}
.blue {
background: blue;
}
</style>
注意:需要滚动的盒子的高度必要小于内容的高度,并且设置overflow:hidden
这里注册了scroll事件和scrollToElement方法,其他的事件和方法操作都是一样的,详细请看官方文档:better-scroll官方地址