如何为嵌套规则(CSS)编写选择器(querySelectorAll)?

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

假设我有以下 CSS:

#potionButtonContainer > .potionCellDiv .potionButton, #potionButtonContainer > .potionCellDiv .potionButtonDisabled, #potionButtonContainer > .potionCellDiv .potionButtonActive { background-color: rebeccapurple }

可以写得短一点以避免重复:

#potionButtonContainer > .potionCellDiv { & .potionButton, & .potionButtonDisabled, & .potionButtonActive { background-color: rebeccapurple } }

#potionButtonContainer > .potionCellDiv { .potionButton, .potionButtonDisabled, .potionButtonActive { background-color: rebeccapurple } }

如何使用 querySelectorAll 来使用/编写这样一个缩短的选择器?也许这根本不可能?

当我写作时

document.styleSheets[0].insertRule("#potionButtonContainer > .potionCellDiv { .potionButton, .potionButtonDisabled, .potionButtonActive { background-color: rebeccapurple } }")

然后通过

查询该规则

document.styleSheets[0].cssRules[0].selectorText

它给了我

'#potionButtonContainer > .potionCellDiv'
。该规则有一个嵌套规则

document.styleSheets[0].cssRules[0].cssRules[0]

其中

selectorText
'.potionButton, .potionButtonDisabled, .potionButtonActive'

所以也许我必须使用带有重复的选择器或嵌套那些

querySelectorAll

现在我坚持

#potionButtonContainer > .potionCellDiv .potionButton, #potionButtonContainer > .potionCellDiv .potionButtonDisabled, #potionButtonContainer > .potionCellDiv .potionButtonActive

在 JavaScript 中。

javascript css-selectors
1个回答
0
投票

获取药剂单元格div并查询其中的按钮:


    const potionCellDiv = document.querySelector('#potionButtonContainer .potionCellDiv');
    const buttons = potionCellDiv.querySelectorAll('.potionButton, .potionButtonDisabled, .potionButtonActive');


© www.soinside.com 2019 - 2024. All rights reserved.