8種Web Components中引入外部CSS的方法

01、@import
const template = document.createElement('template');class WhatsUp extends htmlElement {connectedCallback() {const shadowRoot = this.attachShadow({mode: 'open'});shadowRoot.innderhtml = `<style>@import "./index.css"; // 核心代碼</style><div>Sup</div>`}}window.customElements.define('whats-up', WhatsUp);
優(yōu)點:此方法兼容性非常好,點擊查看caniuse。
缺點:性能
02、::part
::part CSS 偽元素表示在陰影樹中任何匹配 part 屬性的元素。
示例代碼
HTML
<template id="whats-up"><div part="sup">Sup</div><div part="foo">Sup</div></template><whats-up></whats-up>
CSS
whats-up::part(sup) {/* 樣式作用于 `sup` 部分 */}whats-up::part(foo) {/* 樣式作用于 `foo` 部分 */}
優(yōu)點:簡潔明了
缺點:兼容性不太好,點擊查看caniuse。
03、var
CSS自定義屬性可以穿透到 Shadow DOM中!
示例代碼
js
const template = document.createElement('template');template.innerHTML = `<style>button {background: var(--background);color: var(--color);padding: var(--padding);font-size: var(--font-size);border: 0;}</style><div>Sup</div>`;
CSS
whats-up {--background: #1E88E5;--color: white;--padding: 2rem 4rem;--font-size: 1.5rem;}
優(yōu)點:兼容性好
缺點:比較局限,只能外部定幾個,樣式不能“自由飛翔”
04、通過屬性傳入
示例代碼
js
class Whatsup extends HTMLElement {static get observedAttributes() {return ['css']}constructor() {super();}get css() {return this.getAttribute('css');}set css(value) {if (value === null || value === false) {this.removeAttribute('css');} else {this.setAttribute('css', value);}}connectedCallback() {const shadowRoot = this.attachShadow({mode: 'open'});shadowRoot.innerHTML = `<style>:host{display: flex;}${this.css} // 核心代碼</style><div>Sup</div>`;}}
HTML
<whats-upcss=".name{color: red;}"></whats-up>
優(yōu)點:樣式可以隨意修改
缺點:代碼不夠優(yōu)雅
05、自定義組件內(nèi)部定義修改樣式函數(shù)
示例代碼
JS
class Whatsup extends HTMLElement {// ...// 核心代碼reStyle(els, styles) {const elements = Array.isArray(els) ? els : [els];elements.forEach((element) => Object.assign(element.style, styles));}}
HTML
<whats-up></whats-up><script>const myEle = document.querySelector('whats-up')const title = myEle.shadowRoot.querySelector('.title');myEle.reStyle(title, {color: 'red',width: '200px',})</script>
06、通過 slot 外部設(shè)置樣式
示例代碼
JS
class WhatsUp extends HTMLElement {constructor() {super();const shadowRoot = this.attachShadow({ mode: 'open' });shadowRoot.innerHTML = `<div><slot name="header"></slot></div>`;}}customElements.define('whats-up', WhatsUp);
HTML
<style>.header{color: red;}</style><whats-up><div slot="header" class="header">what's up</div></whats-up>
07、fetch獲取
示例代碼
class WhatsUp extends HTMLElement {constructor() {super();const shadowRoot = this.attachShadow({ mode: 'open' });// 獲取樣式fetch('./index.css').then(res => res.text()).then(data => {let node = document.createElement('style');node.innerHTML = data;this.shadowRoot.appendChild(node);});// ...}}customElements.define('whats-up', WhatsUp);
優(yōu)點:優(yōu)點是兼容性不錯,支持Shadow DOM的元素均支持此語法;以及性能還OK
缺點:不優(yōu)雅
08、CSS module import
此方法使用瀏覽器原生的import語法,但是import的是CSS文件而不是JS文件。
也就是把CSS文件直接作為模塊引入。
示例代碼
import styles from "index.css";class WhatsUp extends HTMLElement {constructor() {// ...// 核心代碼shadow.adoptedStyleSheets = [styles];}}
優(yōu)點:優(yōu)點是使用方便快捷且是官方推薦方法,或者是import CSS模塊就是為了這個場景才支持的;以及性能OK,import本身就是異步過程。
缺點:兼容性不佳,狠狠戳這里caniuse。
總結(jié)
各種方法適用場景各不相同,小心食用。
學習更多技能
請點擊下方公眾號
![]()


評論
圖片
表情
