[英]How to style different colors (auto highlight) to html elements
.one{color:red} .two{color:blue} .three{color:yellow} .four{color:green}
<html> <span class="one">1</span> <span class="two">2</span> <span class="three">3</span> <span class="four">4</span> <span class="two">2</span> <span class="two">2</span> <span class="one">1</span> <span class="four">4</span> <span class="three">3</span> <span class="three">3</span> <span class="two">2</span> <span class="one">1</span> </html>
I want to display a bunch of text with different colors, here I take number for example. 我想显示一堆颜色不同的文本,这里我以数字为例。 Is there a simple way to highlight different text based on their content, like code editor? 有没有一种简单的方法可以根据内容突出显示不同的文本,例如代码编辑器? Here I have to hard code the css color class. 在这里,我必须对CSS颜色类进行硬编码。
You can use data-attribute that you can target with CSS. 您可以使用可以与CSS一起定位的数据属性。 You simply change the content of the attribute (like you will do with html content) and the CSS will be applied automatically. 您只需更改属性的内容(就像处理html内容一样),就会自动应用CSS。
[content]:before { content: attr(content); } [content="1"] {color: red} [content="2"] {color: blue} [content="3"] {color: yellow} [content="4"] {color: green} [content="text"] {color: brown}
<span content="1"></span> <span content="2"></span> <span content="3"></span> <span content="4"></span> <span content="3"></span> <span content="4"></span> <span content="2"></span> <span content="1"></span> <span content="text"></span>
The answer is - JavaScript! 答案是-JavaScript! 🎉 🎉
Given some elements on your DOM, one can do the following: 给定DOM上的某些元素,就可以执行以下操作:
HTML 的HTML
<span id="mySpan">2</span>
JS JS
const myColors = {0: 'black', 2: 'red', 3:'green'};
const el = document.getElementById('mySpan');
const spanContent = Number(el.innerText) // el.innerHTML will work here as well
el.style.color = myColors[spanContent];
You can read more here: https://www.w3schools.com/js/js_htmldom_css.asp 您可以在这里阅读更多信息: https : //www.w3schools.com/js/js_htmldom_css.asp
EDIT: 编辑:
For bulk operations, we can do the following: 对于批量操作,我们可以执行以下操作:
HTML (note that there's no meaning to the classes, just a copy paste from original Q) HTML(请注意,这些类没有意义,只是原始Q的复制粘贴)
<span class="one">1</span>
<span class="two">2</span>
<span class="three">3</span>
<span class="four">4</span>
<span class="two">2</span>
<span class="two">2</span>
<span class="one">1</span>
<span class="four">4</span>
<span class="three">3</span>
<span class="three">3</span>
<span class="two">2</span>
<span class="one">1</span>
JS JS
const myColors = {0: 'black', 2: 'red', 3:'green'};
const toNumber = n => Number(n) || 0;
const els = document.getElementsByTag('span');
for(const el of els){ // Using ES6
el.style.color= myColors[toNumber(el.innerText)] // el.innerHTML will work here as well
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.