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



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

我的组件正在使用ShadowDOM,我想从CSS访问HTML标签属性。

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

我尝试使用[data-whatintent=keyboard]html[data-whatintent=keyboard]等CSS选择器,但没有奏效。

这是我的 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;
}

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

Supersharp的答案是正确的,但它不是StencilJS代码,而且主机上下文支持也是脆弱的(在Firefox和IE11中不起作用(。

您可以将属性"传输"到主机元素,然后使用主机组件样式内部的选择器:

多伦多证券交易所:

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 属性动态更改,请使其成为组件的属性,并让侦听器函数更新组件。您可以选择使用该属性向主机添加/删除类以进行样式设置,但您也可以继续使用属性选择器。

多伦多证券交易所:

@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)
    );
}

你最好使用 :host-context(( 在 Shadow 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>

最新更新