概述Constructable Stylesheets 允许通过 `new CSSStyleSheet()` 创建样式并在文档或 Shadow DOM 中复用,避免重复 `<style>` 标签与字符串拼接,提高性能与可维护性。用法/示例const sheet = new CSSStyleSheet() sheet.replaceSync(`.btn{padding:8px 12px;background:#4f46e5;color:#fff}`) document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet] class MyEl extends HTMLElement { constructor(){ super() const root = this.attachShadow({ mode: 'open' }) root.adoptedStyleSheets = [sheet] root.innerHTML = `<button class="btn">Click</button>` } } customElements.define('my-el', MyEl) 工程建议将通用样式集中为可复用的 `CSSStyleSheet`,避免多处 `<style>` 重复。对不支持环境降级为 `<style>` 标签或构建时内联;注意跨浏览器兼容。管理样式生命周期与版本,避免无意覆盖与内存泄漏。参考与验证MDN:CSSStyleSheet — https://developer.mozilla.org/docs/Web/API/CSSStyleSheetweb.dev:Constructable Stylesheets — https://web.dev/articles/constructable-stylesheets

发表评论 取消回复