简体   繁体   English

根据名称定义 CSS 背景色

[英]defining a CSS background-color based on name

Knowing that you can define properties of an id/class like this知道您可以像这样定义 id/class 的属性

[id^="word-"]

But can you take that a step further and define the background-color based on the word that follows?但是你能更进一步,根据后面的词定义背景颜色吗? For instance, if I called a bunch of classes: word-black, word-red, word-green, etc. Could I have one CSS class that finds the word after the "-" ie.例如,如果我调用了一堆classes: word-black, word-red, word-green, etc. 。我可以有一个 CSS class 来找到“-”之后的单词吗? black, red, green, etc.黑色、红色、绿色等

Something like: [class^="word-"] {background-color = parsedClassName}类似于: [class^="word-"] {background-color = parsedClassName}

In my opinion that is impossible to do with pur css. But with Javascript you can do it.在我看来,使用 pur css 是不可能的。但是使用 Javascript 你可以做到。

example 1示例 1

 const bgs = document.querySelectorAll('.dyn'); const r = document.querySelector(':root'); bgs.forEach(bg => { const c = bg.classList[0].split('-')[1]; bg.style.setProperty('--bg-color', c); })
 :root { --bg-color: red; } div[class^="word-"] { background-color: var(--bg-color); color: white; }
 <div class="word-red dyn">hello</div> <div class="word-green dyn">hello</div> <div class="word-lightgreen dyn">hello</div>

example 2示例 2

 const bgs = document.querySelectorAll('.dyn'); const r = document.querySelector(':root'); bgs.forEach(bg => { const c = bg.classList[0].split('-')[1]; bg.style.backgroundColor = c; })
 :root { --bg-color: red; /* default bg*/ } div[class^="word-"] { background-color: var(--bg-color); color: white; }
 <div class="word-red dyn">hello</div> <div class="word-green dyn">hello</div> <div class="word-lightgreen dyn">hello</div>

The answer is yes and no.答案是肯定的,也不是。

Yes.是的。 If you are familiar with bootstrap , it is easily to change the text color using css classes like text-primary, text-danger, text-info.如果您熟悉bootstrap ,可以使用 css 类轻松更改文本颜色,例如 text-primary、text-danger、text-info。 All you need to do is to import the bootstrap stylesheet.您需要做的就是导入引导程序样式表。

No. When any of text colors you want is not being included from bootstrap color stylesheet, we have to write several css classes in stylesheets one by one, step by step (should not be done in JavaScript since it is not an interactive case).不,当你想要的任何文本 colors 没有包含在引导程序颜色样式表中时,我们必须在样式表中一个一个地编写几个 css 类(不应在 JavaScript 中完成,因为它不是交互式案例)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM