本文介绍了根据类名称动态更改变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的东西:

.object {
  $primary-color: blue;
  h1 {
    font-size: 40px;
    color: $primary-color;
  }
  p {
    font-size: 20px;
    color: $primary-color;
  }
}

现在我将有一个蓝色物体.但是,假设我想用红色制作相同的对象,写起来可能很直观

Now I'll be having a blue object. But let's say I want to make the same object but in a red color, it might be intuitive to write

.object red {
  $primary-color: red;
}

,并期望所有的$ primary-color都变为红色,但这在SCSS中无效.我要写的是:

and expect all the $primary-color to change to red, but this is not valid in SCSS. What I have to write is:

.object red {
  $primary-color: red;
  h1 { color: $primary-color; }
  p { color: $primary-color; }
}

如果我这样做,我仍然可以将h1中的40px字体大小和p中的20px字体保持不变,并将所有颜色更改为红色.但是,一旦我的代码变大,它将变得越来越难维护.

If I do it this way, I can still keep the 40px font size in h1 and 20px in p and will change all colors to red. However, once my code gets bigger, this will become harder and harder to maintain.

SCSS是否提供任何工具来使此任务更具模块化和可维护性?

Does SCSS provide any tool to make this task more modular and maintainable?

推荐答案

可以肯定SCSS提供了这样的功能,但是您也可以使用CSS变量使用CSS来做到这一点:

For sure SCSS provide such function but you can also do it with CSS using CSS variables:

.object h1 {
  font-size: 40px;
  color: var(--p, blue);
}

.object p {
  font-size: 20px;
  color: var(--p, blue);
}
.red {
  --p:red;
}
.other-color {
  --p:rgb(15,185,120);
}
<div class="object">
<h1>Blue title</h1>
<p>blue text</p>
</div>
<div class="object red">
<h1>red title</h1>
<p>red text</p>
</div>
<div class="object other-color">
<h1>red title</h1>
<p>red text</p>
</div>

这篇关于根据类名称动态更改变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 13:42