基于Angular 8和Bootstrap 4實(shí)現(xiàn)動(dòng)態(tài)主題切換的示例代碼
效果
首先看看效果:
本文將介紹如何基于Angular 8和Bootstrap 4來(lái)實(shí)現(xiàn)上面的主題切換效果。
設(shè)計(jì)
遵循Bootstrap的設(shè)計(jì),我們會(huì)使用 bootswatch.com 提供的免費(fèi)主題來(lái)實(shí)現(xiàn)上面的效果。Bootswatch為前端程序員提供了多達(dá)21種免費(fèi)的Bootstrap主題,并且提供了API文檔 和 實(shí)例頁(yè)面 ,介紹如何在HTML+jQuery的環(huán)境中實(shí)現(xiàn)主題切換。其實(shí),我們也可以使用Bootstrap官網(wǎng)提供的主題設(shè)計(jì)工具來(lái)設(shè)計(jì)自己的主題,這些自定義的主題也是可以用在本文介紹的方法里的,只需要替換相關(guān)的資源地址就可以。如果你打開(kāi)Bootswatch的API,你就會(huì)看到各種主題的元數(shù)據(jù)信息,我們可以使用其中的cssMin鏈接來(lái)替換主頁(yè)的link地址,以達(dá)到切換主題的目的。
在開(kāi)工之前,還是要做一些粗略的設(shè)計(jì)。為了簡(jiǎn)單起見(jiàn),我使用Bootstrap的Navbar來(lái)完成這個(gè)功能,因?yàn)镹avbar的代碼可以直接從Bootstrap官網(wǎng)拷貝過(guò)來(lái),稍微改改就行。不同的是,我將Navbar封裝在一個(gè)組件(Component)里,這樣做的好處是,可以將切換主題的功能封裝起來(lái),以實(shí)現(xiàn)模塊化的設(shè)計(jì)。下圖展示了這一設(shè)計(jì):
基本流程如下:
- theme.service.ts提供從Bootswatch獲取主題信息的服務(wù)
- 主應(yīng)用app.component.ts調(diào)用theme.service.ts,獲取主題信息,并將主題信息綁定到nav-bar.component.ts組件
- 第一次執(zhí)行站點(diǎn),站點(diǎn)會(huì)使用定義在environment.ts中的默認(rèn)值作為默認(rèn)主題,當(dāng)每次切換主題時(shí),會(huì)將所選主題綁定到nav-bar.component.ts上,用來(lái)在下拉菜單中標(biāo)注已選主題,并將所選主題名稱保存在LocalStorage,以便下次啟動(dòng)站點(diǎn)時(shí)直接應(yīng)用已選主題
- nav-bar.component.ts組件會(huì)在Navbar上的dropdown中列出所有的主題名稱,并且標(biāo)注所選主題,當(dāng)用戶點(diǎn)擊某個(gè)主題名稱時(shí),就會(huì)觸發(fā)themeSelectionChanged事件,app.component.ts接收到這個(gè)事件后,就會(huì)替換主頁(yè)的link,完成主題設(shè)置
步驟
首先,根據(jù)Bootswatch API所返回的數(shù)據(jù)結(jié)構(gòu),定義一個(gè)數(shù)據(jù)模型:
export class ThemeDefinition { name: string; description: string; thumbnail: string; preview: string; css: string; cssMin: string; cssCdn: string; scss: string; scssVariables: string; } export class Themes { version: String; themes: ThemeDefinition[]; }
然后,創(chuàng)建theme.service.ts服務(wù),用來(lái)調(diào)用Bootswatch API:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { Themes } from '../models/themes'; @Injectable({ providedIn: 'root' }) export class ThemeService { constructor(private http: HttpClient) { } getThemes(): Observable<Themes> { return this.http.get<Themes>('https://bootswatch.com/api/4.json'); } }
接下來(lái),創(chuàng)建Navbar組件,關(guān)鍵代碼部分就是將主題的名稱綁定到dropdown上,并根據(jù)選擇的主題名稱決定當(dāng)前所顯示的主題名稱是否應(yīng)該是active的。當(dāng)然,dropdown的每個(gè)item還應(yīng)該響應(yīng)用戶的點(diǎn)擊事件:
<nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><i class="fab fa-acquisitions-incorporated"></i></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Link</a> </li> <li *ngIf="themes" class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> 主題 </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a *ngFor="let theme of themes.themes" [className]="theme.name === selectedTheme ? 'dropdown-item active' : 'dropdown-item'" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" (click)="onThemeItemSelected($event)">{{theme.name}}</a> </div> </li> </ul> </div> </nav>
Navbar組件的代碼如下:
import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core'; import { Themes } from 'src/app/models/themes'; import { ThemeService } from 'src/app/services/theme.service'; import { ThemeDefinition } from 'src/app/models/theme-definition'; @Component({ selector: 'app-nav-bar', templateUrl: './nav-bar.component.html', styleUrls: ['./nav-bar.component.css'] }) export class NavBarComponent implements OnInit { @Input() themes: Themes; @Input() selectedTheme:string; @Output() themeSelectionChanged : EventEmitter<ThemeDefinition> = new EventEmitter(); constructor(private themeService: ThemeService) { } ngOnInit() { } onThemeItemSelected(event: any) { const selectedThemeName = event.target.text; const selectedTheme = this.themes.themes.find(t => t.name === selectedThemeName); this.themeSelectionChanged.emit(selectedTheme); } }
在onThemeItemSelected事件處理函數(shù)中,會(huì)讀取被點(diǎn)擊dropdown item的名稱,根據(jù)該名稱找到所選的主題,然后將其作為事件數(shù)據(jù),發(fā)起themeSelectionChanged事件,然后,就是app.component.ts來(lái)處理這個(gè)事件了。在該事件處理函數(shù)中,從事件數(shù)據(jù)獲取主題信息,然后調(diào)用applyTheme方法來(lái)應(yīng)用主題:
import { Component, OnInit } from '@angular/core'; import { ThemeDefinition } from './models/theme-definition'; import { Themes } from './models/themes'; import { ThemeService } from './services/theme.service'; import { environment } from 'src/environments/environment'; import { StorageMap } from '@ngx-pwa/local-storage'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'nblogger'; themes: Themes; selectedTheme: string; constructor(private themeService: ThemeService, private storage: StorageMap) { } ngOnInit() { this.themeService.getThemes() .subscribe(data => { this.themes = data; this.storage.get('app-theme-name').subscribe(name => { const themeName = name ? name : environment.defaultTheme; const currentTheme = this.themes.themes.find(t => t.name === themeName); this.applyTheme(currentTheme); }); }); } onThemeSelectionChanged(event: ThemeDefinition) { this.applyTheme(event); } private applyTheme(def: ThemeDefinition): void { this.storage.set('app-theme-name', def.name).subscribe(()=>{}); this.selectedTheme = def.name; const links = document.getElementsByTagName('link'); for(let i = 0; i < links.length; i++) { const link = links[i]; if (link.getAttribute('rel').indexOf('style') !== -1 && link.getAttribute('type').indexOf('text') !== -1) { link.setAttribute('href', def.cssMin); } } } }
在applyTheme方法中,首先會(huì)將所選主題名稱設(shè)置到LocalStorage中,以便下次打開(kāi)頁(yè)面的時(shí)候能夠直接應(yīng)用主題;然后,從當(dāng)前document中找到所需的link tag,并將其href值替換為所選主題信息的cssMin鏈接地址(內(nèi)容可以參考Bootswatch的API結(jié)果)以此完成主題替換。
當(dāng)重新打開(kāi)頁(yè)面時(shí),app.component.ts中的ngOnInit初始化方法會(huì)被首先調(diào)用,它會(huì)通過(guò)theme.service.ts來(lái)讀取主題信息,之后判斷LocalStorage中是否有已經(jīng)設(shè)置好的主題。如果有,則使用該主題,否則就從environment.ts的默認(rèn)值中選擇主題名稱進(jìn)行設(shè)置。
app.component.ts所使用的template就比較簡(jiǎn)單,主體是對(duì)Navbar組件的引用,還可以加一些額外的HTML元素進(jìn)行效果測(cè)試:
<app-nav-bar [themes]="themes" [selectedTheme]="selectedTheme" (themeSelectionChanged)="onThemeSelectionChanged($event)"></app-nav-bar> <div class="container"> <article> <h1>Heading 1</h1> <h2>Heading 2</h2> <h3>Heading 3</h3> <h4>Heading 4</h4> </article> <div class="alert alert-primary" role="alert"> 這是一個(gè)警告框 </div> <div class="alert alert-secondary" role="alert"> A simple secondary alert—check it out! </div> <div class="alert alert-success" role="alert"> A simple success alert—check it out! </div> <div class="alert alert-danger" role="alert"> A simple danger alert—check it out! </div> <div class="alert alert-warning" role="alert"> A simple warning alert—check it out! </div> <div class="alert alert-info" role="alert"> A simple info alert—check it out! </div> <div class="alert alert-light" role="alert"> A simple light alert—check it out! </div> <div class="alert alert-dark" role="alert"> A simple dark alert—check it out! </div> <button type="button" class="btn btn-primary">Primary</button> <button type="button" class="btn btn-secondary">Secondary</button> <button type="button" class="btn btn-success">成功</button> <button type="button" class="btn btn-danger">失敗</button> <button type="button" class="btn btn-warning">警告</button> <button type="button" class="btn btn-info">信息</button> <button type="button" class="btn btn-light">Light</button> <button type="button" class="btn btn-dark">Dark</button> <button type="button" class="btn btn-link">Link</button> </div>
當(dāng)然,記得在index.html中加入link的占位符,以便上面的applyTheme方法能夠找到它:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Nblogger</title> <base href="/" rel="external nofollow" > <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico" rel="external nofollow" > <link rel="stylesheet" type="text/css" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" > </head> <body> <app-root></app-root> </body> </html>
總結(jié)
我們可以將Bootswatch的所有主題下載到本地,由本地服務(wù)來(lái)提供主題的API,這樣切換主題會(huì)變得更快,也可以自己自定義主題然后擴(kuò)展這個(gè)自制的本地API來(lái)提供更豐富的主題,根據(jù)需要來(lái)定吧。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
angularJS模態(tài)框$modal實(shí)例代碼
本篇文章主要介紹了angularJS模態(tài)框$modal實(shí)例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05Ionic + Angular.js實(shí)現(xiàn)驗(yàn)證碼倒計(jì)時(shí)功能的方法
驗(yàn)證碼倒計(jì)時(shí)這個(gè)功能相信對(duì)大家每個(gè)人來(lái)說(shuō)都不陌生,之前介紹了在Android中的實(shí)現(xiàn)方法,下面這篇文章主要給大家介紹了利用Ionic + Angular.js實(shí)現(xiàn)驗(yàn)證碼倒計(jì)時(shí)功能的相關(guān)資料,文中介紹的非常詳細(xì),需要的朋友們下面來(lái)一起看看吧。2017-06-06詳解Angular CLI + Electron 開(kāi)發(fā)環(huán)境搭建
本篇文章主要介紹了Angular CLI + Electron 開(kāi)發(fā)環(huán)境搭建,具有一定的參考價(jià)值,有興趣的可以了解一下2017-07-07Angular中ng-options下拉數(shù)據(jù)默認(rèn)值的設(shè)定方法
本篇文章主要介紹了Angular中ng-options下拉數(shù)據(jù)默認(rèn)值的設(shè)定方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06Angular5中調(diào)用第三方庫(kù)及jQuery的添加的方法
這篇文章主要介紹了Angular5中調(diào)用第三方庫(kù)及jQuery的添加的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-06-06angular.js和vue.js中實(shí)現(xiàn)函數(shù)去抖示例(debounce)
這篇文章主要介紹了angular.js和vue.js中實(shí)現(xiàn)函數(shù)去抖示例(debounce),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01AngularJS使用ng-options指令實(shí)現(xiàn)下拉框
這篇文章主要介紹了AngularJS使用ng-options指令實(shí)現(xiàn)下拉框效果,ng-option指令使用也很簡(jiǎn)單,下文具體給大家說(shuō)明,對(duì)angularjs 下拉框知識(shí)感興趣的朋友一起看下吧2016-08-08