当better-scroll真的遇上angular

本文分享了在Angular项目中使用better-scroll的经验,通过html、less和ts文件的配置,解决遇到的滚动难题,包括子容器高度限制和类选择器应用的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于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
    })
  }
}

坑说明

  1. 子容器的高度必须大于父容器,否则无法滚动。
  2. 子容器的高度不能高于父容器太多,不然你上拉的时候,子容器就消失不见了
  3. new BScroll的时候,不能用类选择器,得用 ElementRef

由于设备原因,以上代码是我从另一个项目中剪切过来的,我暂时没法测试,不过讲道理应该跑的通。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值