better-scroll的基本使用
作者:
秒速五厘米
better-scroll是借鉴iscroll,是很牛的前端大神ustbhuangyi黄轶老师上传至github,并在教学视频中屡次运用的
github地址:https://github.com/ustbhuangyi/better-scroll
中文文档:Document
其方法、事件、属性等都可以去文档查找,做移动端的滑动非常好
---------------------
必须包含两个大的div,外层和内层div
外层div设置可视的大小(宽或者高)-有限制宽或高
内层div,包裹整个可以滚动的部分
内层div高度一定大于外层div的宽或高,才能滚动
### 2、基本使用
new BScroll(Dom元素) //其中DOM元素就是外层的div, //这里要注意的是,better-scroll 只处理容器(wrapper)的第一个子元素(content)的滚动, 其它的元素都会被忽略。
better-scroll 最常见的应用场景是列表滚动,我们来看一下它的 html 结构
<div class="wrapper"> <ul class="content"> <li>...</li> <li>...</li> ... </ul> </div>
css
/*对外层div进行了高度上的限制*/
.wrapper{
display: fixed;
left: 0;
top: 0;
bottom: 0;
width: 100%;
overflow:hidden;
}上面的代码中 better-scroll 是作用在外层 wrapper 容器上的,滚动的部分是 content 元素。
import BScroll from 'better-scroll'
let wrapper = document.querySelector('.wrapper')
let scroll = new BScroll(wrapper)场景:vue
<div class="pic-wrapper" ref='picWrapper'>
<ul class="pic-list" ref='picList'>
<li class="pic-item" v-for="pic in seller.pics">
<img :src="pic"/>
</li>
</ul>
</div>
css
.pic-wrapper{
padding-bottom: 18px;
width: 100%;
overflow: hidden;
.pic-list{
font-size: 0;
white-space: nowrap;
.pic-item{
display: inline-block;
margin-right: 6px;
width: 120px;
height: 90px;
&:last-child{
margin-right: 0;
}
img{
width: 100%;
height: 100%;
}
}
}
}js
if(!this.picScroll){
this.picScroll = new Bscroll(this.$refs.picWrapper,{
scrollX: true,
eventPassthrough: 'vertical'
})
}else{
this.picScroll.refresh();
}<div class="slider" ref="slider"> <div class="slider-group" ref="sliderGroup"> <div v-for="item in slider"> <a :href="item.linkUrl"> <img :src="item.picUrl"/> </a> </div> </div> </div>
//初始化slider轮播
this.slider = new Bscroll(this.$refs.slider,{
scrollX: true,
scrollY: false,
momentum: false,
snap: {
loop: this.loop,
threshold: 0.3,
speed: 400
},
bounce: false,
stopPropagation: true,
click: true
})横向滚动时 必须设置内层盒子的宽度 否则不能滚动