有没有一种方法可以在Shadow-DOM中访问CSS中的HTML标签属性?

时间:2019-03-28 18:17:29

标签: html css typescript shadow-dom stenciljs

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

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

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

我尝试过使用[data-whatintent=keyboard]html[data-whatintent=keyboard]之类的CSS选择器,但是没有用。

这是我要从其访问data-whatintent属性的HTML标记:

<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属性的值在组件上设置样式,以便轮廓像我想要的。

2 个答案:

答案 0 :(得分:2)

您可以根据使用自定义元素的上下文,使用: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>

答案 1 :(得分:2)

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

您可以将属性“转移”到宿主元素,然后从宿主组件样式内部使用选择器:

TSX:

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

TSX:

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