有没有办法在 Shadow-DOM 中访问 CSS 中的 HTML 标签属性?

Is there a way of accessing HTML tag attribute in CSS within Shadow-DOM?

我正在使用 StencilJS 创建一个自定义组件,当用户使用键盘或鼠标导航到该组件时,我必须对轮廓进行一些更改。

我的组件正在使用 ShadowDOM,我想从 CSS.

访问一个 HTML 标签属性

标签的属性是用 what-input (https://github.com/ten1seven/what-input) 生成的,用于检测键盘和鼠标事件。

我试过使用 CSS 选择器,例如 [data-whatintent=keyboard]html[data-whatintent=keyboard],但没有用。

这是我的 HTML 标签,我想从中访问 data-whatintent 属性:

<html dir="ltr" lang="en" data-whatinput="keyboard" data-whatintent="mouse">

  <my-custom-component></my-custom-component>

</html>

这是我的 CSS:

[data-whatintent=keyboard] *:focus {
  outline: solid 2px #1A79C6;
}

我希望我的 CSS 在 ShadowDOM 中可以使用 data-whatintent 属性的值来设置我的组件的样式,这样轮廓就像我想要的那样。

您应该使用 :host-context() 在阴影 DOM 中应用 CSS 样式,具体取决于使用自定义元素的上下文。

customElements.define( 'my-custom-component', class extends HTMLElement {
    constructor() {
        super()
        this.attachShadow( { mode: 'open' } )
            .innerHTML = `
              <style>
                :host-context( [data-whatinput=keyboard] ) *:focus {
                   outline: solid 2px #1A79C6;
                }
              </style>
              <input value="Hello">`
    }
} )         
           
<html dir="ltr" lang="en" data-whatinput="keyboard" data-whatintent="mouse">

  <my-custom-component></my-custom-component>

</html>

Supersharp 的回答是正确的,但它不是 StencilJS 代码,而且主机上下文支持也很古怪(在 Firefox 和可能的 IE11 中不起作用)。

您可以'transfer'将属性添加到宿主元素,然后使用宿主组件样式中的选择器:

多伦多证券交易所:

private intent: String;

componentWillLoad() {
    this.intent = document.querySelector('html').getAttribute('data-whatintent');
}

hostData() {
    return {
        'data-whatintent': this.intent
    };
}

SCSS:

:host([data-whatintent="keyboard"]) *:focus {
    outline: solid 2px #1A79C6;
}

如果 data-whatintent 属性动态变化,使它成为组件的 属性,并让侦听器函数更新您的组件。您可以选择使用 属性 到 add/remove 类 到主机进行样式设置,尽管您也可以继续使用属性选择器。

多伦多证券交易所:

@Prop({ mutable: true, reflectToAtrr: true }) dataWhatintent: String;

componentWillLoad() {
    this.dataWhatintent = document.querySelector('html').getAttribute('data-whatintent');
}

hostData() {
    return {
        class: { 
            'data-intent-keyboard': this.dataWhatintent === 'keyboard' 
        }
    };
}

SCSS:

:host(.data-intent-keyboard) *:focus {
    outline: solid 2px #1A79C6;
}

文档的键盘和鼠标事件处理程序:

function intentHandler(event: Event) {
    const intent = event instanceof KeyboardEvent ? 'keyboard' : 'mouse';
    document.querySelectorAll('my-custom-component').forEach(
        el => el.setAttribute('data-whatintent', intent)
    );
}