@@ -128,6 +128,38 @@ function restoreOrder(storageKey, elementClass) {
128128 }
129129}
130130
131+ // CSS 作用域化函数
132+ function scopeCSS ( cssText , scopeSelector ) {
133+ // 使用正则表达式为每个规则添加作用域前缀
134+ return cssText . replace (
135+ / ( [ \w \W ] + ?) \{ ( [ \w \W ] + ?) \} / g,
136+ ( match , selectors , rules ) => {
137+ // 处理每个选择器
138+ const scopedSelectors = selectors . split ( ',' )
139+ . map ( selector => {
140+ const trimmed = selector . trim ( ) ;
141+ // 跳过已包含作用域的选择器
142+ if ( trimmed . includes ( scopeSelector ) ) {
143+ return trimmed ;
144+ }
145+ // 处理伪类和伪元素
146+ if ( trimmed . includes ( ':' ) && ! trimmed . includes ( '::' ) ) {
147+ const parts = trimmed . split ( ':' ) ;
148+ return `${ scopeSelector } ${ parts [ 0 ] } :${ parts [ 1 ] } ` ;
149+ }
150+ // 处理关键帧动画
151+ if ( trimmed . startsWith ( '@keyframes' ) || trimmed . startsWith ( '@media' ) ) {
152+ return trimmed ;
153+ }
154+ return `${ scopeSelector } ${ trimmed } ` ;
155+ } )
156+ . join ( ', ' ) ;
157+
158+ return `${ scopedSelectors } {${ rules } }` ;
159+ }
160+ ) ;
161+ }
162+
131163function scopeEBStyles ( scopeSelector = '[data-eb-styles]' ) {
132164 // 动态重写 CSS 规则
133165
@@ -138,16 +170,13 @@ function scopeEBStyles(scopeSelector = '[data-eb-styles]') {
138170 ebLinks . forEach ( link => {
139171 // 先移除
140172 link . parentNode . removeChild ( link ) ;
141-
173+
142174 // 再改写
143175 fetch ( link . href )
144176 . then ( response => response . text ( ) )
145177 . then ( cssText => {
146178 // 为所有 CSS 规则添加作用域前缀
147- const scopedCSS = cssText . replace (
148- / ( [ \w \W ] + ?) \{ ( [ \w \W ] + ?) \} / g,
149- `${ scopeSelector } $1 {$2}`
150- ) ;
179+ const scopedCSS = scopeCSS ( cssText ) ;
151180
152181 // 创建新的 style 标签
153182 const style = document . createElement ( 'style' ) ;
@@ -163,10 +192,7 @@ function scopeEBStyles(scopeSelector = '[data-eb-styles]') {
163192
164193 // 再添加
165194 const originalCSS = style . textContent ;
166- const scopedCSS = originalCSS . replace (
167- / ( [ \w \W ] + ?) \{ ( [ \w \W ] + ?) \} / g,
168- `${ scopeSelector } $1 {$2}`
169- ) ;
195+ const scopedCSS = scopeCSS ( originalCSS ) ;
170196
171197 // 创建作用域化的新样式
172198 const scopedStyle = document . createElement ( 'style' ) ;
0 commit comments