BScroll初识
BetterScroll
是一款重点解决移动端(已支持 PC)各种滚动场景需求的插件。它是纯 JavaScript 实现,所以它是无依赖。
BetterScroll
是一个开源项目,用在项目中避免自己手动写一个滚动页面。
BScroll怎么用
1. 安装
执行如下命令安装:
npm install @better-scroll --save
复制代码
2. 使用
在script
中引入:
import BScroll from 'better-scroll';
复制代码
然后加载使用:
let bs = new BScroll(wrapper, {})
复制代码
BScroll实践
1. 实例:点击右侧数字导航跳转到相应的内容
实现
- 代码实现
<template>
<!-- wrapper外层 -->
<div class="wrapper" ref="wrapper">
<div>
<!-- content滚动处 左侧详情内容 -->
<div class="content" :ref="index" v-for="index in 10" :key="index">
{{ index }}
</div>
</div>
<!-- 右边导航列 -->
<ul class="alphabet">
<li v-for="index in 10" :key="index + '1'" @click="handleClick">
{{ index }}
</li>
</ul>
</div>
</template>
<script>
//导入
import BScroll from 'better-scroll';
export default {
data(){
return{
nums:"",
};
},
mounted() {
this.init()
},
methods: {
init(){
this.scroll = new BScroll(this.$refs.wrapper,{
//默认点击,所以要设置click:true
click:true
})
},
//获取点击的数字
handleClick(e){
this.nums = e.target.innerText;
console.log(e.target.innerText + "被点击")
//console.log("被点击")
},
},
watch:{
//监听letter变化,跳转到相应内容
nums(){
//调整到对应数字的div
this.scroll.scrollToElement(this.$refs[this.nums][0]);
//console.log(this.$refs[this.nums][0])
},
},
};
</script>
<style>
.wrapper {
position: absolute;
overflow: hidden;
width: 100%;
height: 100%;
background: rgb(186, 209, 175);
}
.content {
height: 200px;
width: auto;
font-size: 20px;
background: rgb(228, 135, 178);
border: 1px rgb(165, 9, 61) solid;
align-items: center;
line-height: 200px;
}
.alphabet {
position: fixed;
right: 0;
top: 150px;
bottom: 0;
text-align: center;
font-size: 30px;
color: aliceblue;
list-style-type:none;
}
</style>
复制代码
- 最终效果
需注意的地方
- 最开始点击事件怎么都不执行,后面查阅文档发现
BetterScroll
默认会阻止浏览器的原生click
事件,所以要在init
初始化的时候设置:init(){ this.scroll = new BScroll(this.$refs.wrapper,{ //默认点击,所以要设置click:true click:true }) } 复制代码
- 提供API:
scrollToElement(el, time, offsetX, offsetY, easing)
滚动到指定的目标元素,上实例中传入一个DOM对象。传入的参数可以是DOM、string、number、boolean、Object
(详见官网)
nums(){
//调整到对应数字的div
this.scroll.scrollToElement(this.$refs[this.nums][0]);
//打印传入的参数
console.log(this.$refs[this.nums][0])
},
复制代码
如果点击4: