Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

html - How to color specific word in a container using CSS

Suppose I have a container:

 <div id="container"> This is a red apple </div>

How to color a word "red" with red color? Something like (pseudocode)

#container:[word="red"]{
   color:red;
}

Is it possible to do this in pure CSS without introducing JavaScript or modifying the existing HTML?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Background

This is a Vanilla JavaScript solution because it ain't possible with CSS. Not joking, read the specification. You can match on an element, the name of an attribute in the element, and the value of a named attribute in an element. I don't see anything for matching content within an element though.

Introduction

Here's my shot at it. I am sure there is a sleeker way, but this is the gist of how it would start off as. Also, since there are a finite number of colors that you will want to colorify, it's nice to use a bunch of if statements like I have.

A better technique of course would be to do it more programmatically by building a color dictionary and hence make the code organized. But this works, and it's Vanilla JS. Apparently, I didn't have expertise in Regex, so I am sure a few lines are unnecessary.

Features

  • Works for multiple color occurrences
  • Works for multiple colors as visible

http://jsfiddle.net/TB62H/5/

var text = document.getElementById("content");
var str = text.innerHTML,
    reg = /red|blue|green|orange/ig; //g is to replace all occurances

//fixing a bit
var toStr = String(reg);
var color = (toStr.replace('/g', '|')).substring(1);

//split it baby
var colors = color.split("|");

if (colors.indexOf("red") > -1) {
    str = str.replace(/red/g, '<span style="color:red;">red</span>');
}

if (colors.indexOf("blue") > -1) {
    str = str.replace(/blue/g, '<span style="color:blue;">blue</span>');
}

if (colors.indexOf("green") > -1) {
    str = str.replace(/green/g, '<span style="color:green;">green</span>');
}

if (colors.indexOf("orange") > -1) {
    str = str.replace(/orange/g, '<span style="color:orange;">orange</span>');
}


document.getElementById("updated").innerHTML = str;

Results

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...