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

问题描述 投票:0回答:2

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

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

使用what-input(qazxsw poi)生成标记的属性以检测键盘和鼠标事件。

我尝试过使用像https://github.com/ten1seven/what-input[data-whatintent=keyboard]这样的CSS选择器,但它没有用。

这是我要从中访问html[data-whatintent=keyboard]属性的HTML标记:

data-whatintent

这是我的CSS:

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

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

</html>

我希望Shadow DOM中的CSS可以使用qazxsw poi属性的值来设置我的组件上的样式,这样轮廓就像我想要的那样。

html css typescript shadow-dom stenciljs
2个回答
2
投票

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

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

TSX:

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

SCSS:

data-whatintent

如果private intent: String; componentWillLoad() { this.intent = document.querySelector('html').getAttribute('data-whatintent'); } hostData() { return { 'data-whatintent': this.intent }; } 属性动态更改,则使其成为组件的属性,并使侦听器函数更新组件。您可以选择使用该属性向主机添加/删除类以进行样式设置,但您也可以继续使用属性选择器。

TSX:

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

SCSS:

data-whatintent

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

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

2
投票

您应该使用:host(.data-intent-keyboard) *:focus { outline: solid 2px #1A79C6; } 在Shadow DOM中应用CSS样式,具体取决于使用自定义元素的上下文。

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()
© www.soinside.com 2019 - 2024. All rights reserved.