Angular5 自定义scrollbar样式之 ngx-malihu-scrollbar

简介

此插件是 Malihu jQuery Scrollbar 为了在 Angular2+ 环境下使用,封装的一个ts的版本。提供directiveservice

从安装量来看,它比不过 perfect-scrollbar,所以我最后也没用它。但是也记录一下用法,万一以后要用呢!

安装

npm install ngx-malihu-scrollbar --save
我当时安装的版本是 `7.0.0`。

添加需要的css和script

这个插件是依赖jQuery的。

_angular-cli.json中添加

    "styles": [
                "../src/scss/styles.scss",
                
                "../node_modules/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.css"
            ],
    "scripts": [
                "../node_modules/jquery/dist/jquery.min.js",
                
                "../node_modules/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.concat.min.js"
            ],

在tsconfig.app.json添加

{
  "compilerOptions": {
    ...
    "types": [
+     "jquery",
+     "mcustomscrollbar"
    ]
  },
  ...
}

使用

在根module中引入

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
+ import { MalihuScrollbarModule } from 'ngx-malihu-scrollbar';
 
import { HomeComponent } from './home.component';
 
@NgModule({
  imports: [
    CommonModule,
+   MalihuScrollbarModule.forRoot(),
  ],
  declarations: [HomeComponent],
})

模板中使用

<ul *ngIf="nodeList.length" class="indented mTop scroll"  [style.max-height.px]="treeContentHeight" malihu-scrollbar [scrollbarOptions]="scrollbarOptions">
   <li class="no_line" *ngFor="let node of nodeList"></li>
</ul>

component中配置options

+ import { MalihuScrollbarService } from 'ngx-malihu-scrollbar';

+ public scrollbarOptions: any = { axis: 'y', theme: 'my-theme'};
constructor(
        private _router: Router,
        private mScrollbarService: MalihuScrollbarService,
    ) {

    }

// 更新

setTreeContentHeight() {
       ...
       // caculate height

       // update scroll
       this.mScrollbarService.update('#scrollContainer');
      
}

自定义的主题样式

在 styles.css 中自定义样式

.mCS-my-theme.mCSB_scrollTools{
    .mCSB_dragger{
        .mCSB_dragger_bar{ background-color: #DEDEE4 !important; }
    } 
    .mCSB_draggerRail{ background-color: transparent !important; }
} 

使用感受:没有perfect-scrollbar流畅,每次滚动条出现时,会先出现浏览器的默认滚动条,然后才渲染出自定义的滚动条,不完美。故,弃用之~

原文地址:https://www.cnblogs.com/liulei-cherry/p/10044476.html