How to color specific word in a container using CSS

后端 未结 14 1684
不思量自难忘°
不思量自难忘° 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:46

    If you don't want to add html/javascript the simpel answer is NO you can't

    Take a look at the following specification http://www.w3.org/TR/css3-selectors/#selectors

    That are all available selectors for CSS3 and therefor it's simply impossible, and that's your answer.

    You have 2 options left without changing the content one is all ready described here:

    • javascript
    • server-side parsing so everything gets wrapped with the span tag
    0 讨论(0)
  • 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<a.length;i++){
          var newSpan=document.createElement("span")
          var words=a[i].nodeValue.replace(/[\r\n]/g,"").split(' ');
            for(var j=0;j<words.length;j++){
                var escapedWord=words[j].replace(/[^a-zA-Z0-9-']/g,'').toLowerCase()
                words[j]='<span word="'+escapedWord+'">'+words[j]+'</span>'
            }
            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.

    0 讨论(0)
  • 2020-12-15 05:48

    Use <span> for this.

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

    CSS:

    .red {
    color: red;
    }
    

    Edit
    It isn't possible without any additional Javascript or HTML. According to the CSS3 specification there is no such selector (There were thoughts about a :contains() selector for CSS3). Also see this and this Question.

    0 讨论(0)
  • 2020-12-15 05:49
    1. It cannot be done using only css selectors at present checkout documentation for CSS selectors

    It can be easily Done with Jquery with a single line statements

    Check Out the Demo

    Highlighting and remove highlight on button click

    The Simplest Solution when You Select a specific word with mouse that word would be highlighted throughout the Container

    Jquery

    var text = $('div').text().replace(/Ipsum/g,"<span class='red'>Ipsum</span>");
    $('div').html(text);
    

    EDIT:

    $('#id1').click(
        function(){
        var text = $('div').text().replace(/Ipsum/g,"<span class='red'>Ipsum</span>");
    $('div').html(text);
        }
    );
    
    $('#id2').click(
      function(){
          $( "span.red" ).each(function() {
      $( this ).contents().unwrap();
    
    });
    
        }
    );
    

    CSS

    .red {
    color: red;
    }
    

    HTML

    <div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
     </div>
    

    EDIT:

    <input type="button" value="Click to highlight" id="id1" />
    <input type="button" value="Click to remove highlight" id="id2" />
    

    0 讨论(0)
  • 2020-12-15 05:53

    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

    0 讨论(0)
  • 2020-12-15 05:57

    You should use the span tag to surround the word "red"

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

    Then select this span using

    #container span {
        color: red;
    }
    
    0 讨论(0)
提交回复
热议问题