SCSS:动态定位与父级具有相同前缀类的子级?



使用 SCSS,是否可以告诉子元素仅在与其父元素共享(前缀(类时才接收某种样式,而不知道类的具体名称,只知道前缀?

我想避免编写特定的规则来告诉每个具有特定类的孩子,当父母具有相同的特定类时,它应该如何表现。相反,我想创建一个规则,通常规定:"每当父级和子级共享同一类时,子级都会收到这种样式:...«

(前缀旨在帮助区分需要子项匹配的类与处理子项外观其他方面的其他类。

一个Javascript,相当于我所说的:

const parent = document.getElementById("parent");
const children = parent.querySelectorAll("child");
const prefix = "myClassPrefix_";
// Get prefixed class from parent
let prefixedClass_parent = Array.prototype.filter.call(parent.classList, function (className) {
if(className.includes(prefix)) {
return className
}
});
// Check if child shares class
for (let i = 0; i < children.length; i++) {
// Apply styles to child with matching class
if(children[i].classList.contains(prefixedClass_parent)) {
children[i].style.opacity = 1;
}  
}

你不能单独使用 scss,因为它会打印出 css,并且任何关于prefix-DYNAMIC动态值的逻辑都会丢失。

您可以做的是在前缀之后有一个类名的可能值的 scss 集合,并以这种方式打印所有这些值:

$classIds: example example2 example3 example4;
@each $classId in $classIds {
.prefix-#{$classId} .prefix-#{$classId} {
background: yellow;
}
}

这将导致:

.prefix-example .prefix-example {
background: yellow;
}
.prefix-example2 .prefix-example2 {
background: yellow;
}
.prefix-example3 .prefix-example3 {
background: yellow;
}
.prefix-example4 .prefix-example4 {
background: yellow;
}
<div class="prefix-example2">
<div class="prefix-example1">Lorem ipsum</div>
<div class="prefix-example2">Lorem ipsum</div>
<div class="prefix-example3">Lorem ipsum</div>
<div class="prefix-example4">Lorem ipsum</div>
</div>

您也可以使用前缀作为标识符,在这种情况下,任何与其父级共享前缀的子项都将采用样式(纯 css(:

div[class^="prefix2-"] div[class^="prefix2-"]{
background: yellow;
}
<div class="prefix2-example">
<div class="prefix1-example">Lorem ipsum</div>
<div class="prefix2-example">Lorem ipsum</div>
<div class="prefix3-example">Lorem ipsum</div>
<div class="prefix4-example">Lorem ipsum</div>
</div>

最新更新