【问题标题】:SCSS: Dynamically target child with same prefixed class as parent?SCSS:动态定位具有与父级相同前缀类的子级?
【发布时间】:2020-07-08 08:14:18
【问题描述】:

使用 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;
  }  
}

【问题讨论】:

    标签: sass


    【解决方案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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多