How to color specific word in a container using CSS

后端 未结 14 1687
不思量自难忘°
不思量自难忘° 2020-12-15 05:01

Suppose I have a container:

 
This is a red apple

How to color a word \"red\" with red color? Some

14条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 05:47

    Now if you allow me to use just a bit of javascript, and perhaps the caveat that I have no idea how well this will scale, might break a lot of CSS, and the implementation is a bit shoddy. That said, I think we can simply give css a bit of a hand by rewriting the HTML.

    As you know we can add spans around the words and we can select that. But instead of just selecting the chosen one and attaching the style information, we span all the words. And attach the word as an value to the attribute "word". With the help of a way to get all the textNodes, it might look something like

    //adapted from https://stackoverflow.com/a/10730777/1480215
    function makeHighlightable(){
      var n, a=[], walk=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,null,false);
      while(n=walk.nextNode()) a.push(n);
        for(var i=0;i'+words[j]+''
            }
            words=words.join(" ")
            newSpan.innerHTML=words
            a[i].parentNode.replaceChild(newSpan,a[i])
        }
    }
    
    makeHighlightable()
    

    With that in place, you can now do

    #container [word=red]{ /* space instead of : */
        color:#F00;
    }
    

    Demo

    and it might possibly work.

提交回复
热议问题