And*_*rew 13 css web-component shadow-dom
有没有办法改变阴影元素中的样式?具体来说,扩展/覆盖在css 类中找到的一些属性?我正在使用名为Beanote的chrome扩展程序,自2017年4月(2017年)以来尚未更新,我想修复一个讨厌的错误.我发现一行css补丁对我来说足够了,但是我不知道如何应用它而不进入阴影元素本身并直接在开发工具中编辑这些样式.
我正在寻找一种方法:
/*global css rule*/
.the-class-name { property-name: my-value; }
Run Code Online (Sandbox Code Playgroud)
覆盖这个:
/* style tag inside the shadow-root */
.the-class-name { property-name: bad-value; }
Run Code Online (Sandbox Code Playgroud)
大部分的资源,我与涉及网上查询发现shadow-root override style或edit shadow-root styling有一些东西需要做:host,如果它意味着这个,不适合我的需要或喜欢否决的功能工作::shadow.
Sup*_*arp 15
由于样式的隔离(Shadow DOM的一个功能),您无法定义将在Shadow DOM范围中应用的全局CSS规则.
它可以使用CSS变量,但它们应该在阴影组件中显式实现(这与第三方库不同).
解决方法是直接在shadow DOM中注入样式行.
//host is the element that holds the shadow root:
var style = document.createElement( 'style' )
style.innerHTML = '.the-class-name { property-name: my-value; }'
host.shadowRoot.appendChild( style )
Run Code Online (Sandbox Code Playgroud)
注意:它仅在Shadow DOM mode设置为时才有效'open'.
2019年Chrome 73+和Opera 60+的更新
现在可以直接实例化CSSStyleSheet对象并将其影响到Shadow DOM或文档:
var sheet = new CSSStyleSheet
sheet.replaceSync( `.color { color: pink }`)
host.shadowRoot.adoptedStyleSheets = [ sheet ]
Run Code Online (Sandbox Code Playgroud)
Ionic V4选择向下图标颜色更改示例
document.querySelector('#my-select').shadowRoot.querySelector('.select-icon-inner').setAttribute('style', 'opacity:1');
ionViewDidEnter() {
document.querySelector('#my-select').shadowRoot.querySelector('.select-icon-inner').setAttribute('style', 'opacity:1');
}
Run Code Online (Sandbox Code Playgroud)
如果要覆盖默认生成的shadowRoot样式,则必须在页面完全加载后调用js函数。
扩展之前的答案。
外部样式总是胜过 Shadow DOM 中定义的样式,即当您添加引用您正在设置样式的组件的全局样式规则时。请参阅:https ://developers.google.com/web/fundamentals/web-components/shadowdom#stylefromoutside
否则,这将取决于元素影子 DOM 是否嵌入了styleSheet,或者是否采用了使用 的样式表adoptedStyleSheets。
addRule如果元素嵌入在元素中,您可以使用或向现有样式表添加或插入规则insertRule。这也适用于添加了adopedStyleSheets.
正如前面的答案中提到的,您可以将新的样式表附加到采用的样式表列表中。当 ShadowRoot 包含嵌入的styleSheet, 因为adoptedStyleSheets优先并且styleSheetList是只读属性时,这也有效。
assert(myElement.shadowRoot.styleSheets.length != 0);
myElement.shadowRoot.styleSheets[0].addRule(':host', 'display: none;');
assert(myElement.shadowRoot.adoptedStyleSheets.length != 0);
`myElement.shadowRoot.adoptedStyleSheets[0].addRule(':host', 'display: none;');`
const sheet = new CSSStyleSheet();
sheet.replaceSync(`:host { display: none; }`);
const elemStyleSheets = myElement.shadowRoot.adoptedStyleSheets;
// Append your style to the existing style sheet.
myElement.shadowRoot.adoptedStyleSheets = [...elemStyleSheets, sheet];
// Or if just overwriting a style set in the embedded `styleSheet`
myElement.shadowRoot.adoptedStyleSheets = [sheet];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9522 次 |
| 最近记录: |