我正在用StencilJS创建一个自定义组件,当用户使用键盘或鼠标导航到组件时,我必须对大纲做一些更改。
我的组件正在使用ShadowDOM,我希望从CSS访问一个HTML属性。
标记的属性是用什么-输入(https://github.com/ten1seven/what-input)生成的,以检测keybord和鼠标事件。
我尝试过使用CSS选择器,比如[data-whatintent=keyboard]和html[data-whatintent=keyboard],但是它没有起作用。
这是我要访问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属性的值来设置组件上的样式,因此大纲就像我想要的那样。
发布于 2019-03-28 19:08:52
Supersharp的答案是正确的,但是它不是StencilJS代码,而且主机上下文支持也不稳定(在火狐和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)
);
}发布于 2019-03-28 18:41:14
您应该使用*主机-上下文()在Shadow中应用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>
https://stackoverflow.com/questions/55404389
复制相似问题