关于angular中如何使用better-scroll的资料是真滴少,自己尝试了大概有个3天,终于成功了。
别问了,照着做就完事了。
# 1、安装依赖
npm i better-scroll --save
# 2、类型声明文件(好像可以不用装)
npm i @types/better-scroll -D
html文件如下
test.component.html
<div class="wrapper" #wrapper>
<div class="scroll">
当better-scroll真的遇上angular
</div>
</div>
样式文件(我用的是less)如下
test.component.less
.wrapper{
width: 100%; // 宽度无所谓了
height: 100%; // 父容器的高度必须固定
position: relative;
display: block;
overflow: hidden;
.scroll {
display: block;
position: relative;
width: 100%; // 宽度无所谓
height: calc(100% + 1px); // 子容器的高度必须必父容器高,切记,官网有解析原因
}
}
ts文件如下
test.component.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'
import BScroll from 'better-scroll'
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.less']
})
export class HomeComponent implements OnInit, AfterViewInit {
@ViewChild('wrapper') scrollEl: ElementRef
ngAfterViewInit() {
const scroll: any = new BScroll(this.scrollEl.nativeElement, {
click: true
})
}
}
坑说明
- 子容器的高度必须大于父容器,否则无法滚动。
- 子容器的高度不能高于父容器太多,不然你上拉的时候,子容器就消失不见了
- new BScroll的时候,不能用类选择器,得用 ElementRef
由于设备原因,以上代码是我从另一个项目中剪切过来的,我暂时没法测试,不过讲道理应该跑的通。