【问题标题】:Pass integer values from html to scss将整数值从 html 传递到 scss
【发布时间】:2020-04-09 17:53:15
【问题描述】:

我想做这样的事情

html

<div class="myClass" givenValue="myValue">myText</div>

scss

.myClass {
    @if (givenValue < 0) {
        color: red;
    } @else {
        color: black;
    }
}

我们的目标是真正将样式从 html 转移到 scss。例如,在 Angular 中可以使用 ngClass,但这不是我想要做的。

我知道这样做是可能的

html

<div class="fill-color" style="--color: blue;">Test</div>

scss

.fill-color {
  color: var(--color);
}

这是一个想法,但不幸的是,这不是我的解决方案,因为我有一个整数和 @if 语句。

提前感谢您的建议!

【问题讨论】:

    标签: html sass


    【解决方案1】:

    你不能。 SCSS 是预处理。当涉及到 HTML 时,为时已晚。你不再有 SCSS,只有 CSS。

    考虑改用 JavaScript。

    document.querySelectorAll('.myClass').forEach(element => {
      if (element.dataset.givenValue < 0) element.classList.add("negative")
    });
    .myClass {
      color: black;
    }
    
    .myClass.negative {
      color: red;
    }
    <div class="myClass" data-given-value="-1">myText</div>
    <div class="myClass" data-given-value="0">myText</div>
    <div class="myClass" data-given-value="1">myText</div>

    或者在 HTML 到达浏览器之前使用服务器端代码生成类名。

    【讨论】:

      猜你喜欢
      • 2017-09-06
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      • 2021-10-26
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多