【问题标题】:Change style of all occurrences of a string更改所有出现的字符串的样式
【发布时间】:2012-12-20 20:27:21
【问题描述】:

出于品牌原因,我希望每次出现在标题中时,我的网站标题都以与其余内容不同的字体显示。为简单起见,假设我的特殊字体是 Courier,而我的公司名为 SparklePony。所以,像这样的一行,

<h1 class="title">SparklePony Board of Directors</h1>

将在我的网站默认字体 Arial 中显示带有“快递和董事会”中 SparklePony 一词的标题。 (是的,我知道这会很可怕。)

我尝试过使用 jQuery 字符串替换,但我不想 替换 字符串,我只想在 Courier 中看到它(只为那个词添加一个类,或其他东西之类的。)用&lt;span class="sparkle-pony"&gt;SparklePony&lt;/span&gt;替换SparklePony导致整个丑陋的字符串带有标签和所有内容都显示在我的网站上,而不是添加类。

我的字符串替换有问题吗,还是有更好的方法来设置所有出现的字符串的样式?

【问题讨论】:

  • 你用来替换的代码是什么?你替换了innerHTML吗?

标签: javascript jquery css stylesheet markup


【解决方案1】:

你可以这样做 - 指定你想要的选择器 - #('h1') 或按类。

$('.title').html(function(i,v){    
   return v.replace(/SparklePony/g,'<span class="sparkle">SparklePony</span>');
});
​

http://jsfiddle.net/cQjsu/

【讨论】:

    【解决方案2】:

    如果没有看到代码(这在这样的问题中会很重要),最好的猜测是您使用的是 .text() 而不是 .html(),它可以正确解析 HTML。

    【讨论】:

      【解决方案3】:

      它可以做一些整理,但这可能是一个很好的起点:http://jsfiddle.net/c24w/Fznh4/9/

      HTML

      <div id="title">Highlight this blah blah HiGhLiGhT THIS blah</div>
      <button id="clickme">Click to highlight text</button>
      

      CSS

      #title{
        font-family: sans-serif;
        font-size: 20pt;
        margin: 30px 0;
      }
      span.highlight{
        color: #09f;
        font-weight: bold;
      }
      

      JavaScript

      function highlightText(element, phrase, allOccurrences, caseSensitive){
        var modifiers = (allOccurrences ? 'g' : '') + (caseSensitive ? '' : 'i');
        var text = element.innerHTML;
        element.innerHTML = text.replace(new RegExp(phrase, modifiers), function(match){
          return '<span class="highlight">' + match + '</span>';
        });
      }
      
      var button = document.getElementById('clickme');
      var el = document.getElementById('title');
      
      button.onclick = function(){
        highlightText(el, 'highlight this', true, false);
        button.onclick = null;
      };
      

      【讨论】:

        【解决方案4】:

        试试类似的东西:

        $.each($(".title"),function({
        $(this).html($(this).html().replace("SparklePony","<span class='sparkle-pony'>SparklePony</span>"))
        });
        

        【讨论】:

          【解决方案5】:

          又好又短:

          var $body = $("body");
          $body.html($body.html().replace(/SparklePony/ig, "<span class='cool'>SparklePony</span>"));​
          

          但请记住,$("body") 是一个非常昂贵的选择器。您应该考虑更精确的父目标。

          Demo here (fiddle)

          【讨论】:

          • 我现在将其限制为 h1。得分。
          猜你喜欢
          • 2022-11-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-20
          • 2023-04-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多