更改字符串所有出现的样式

Change style of all occurrences of a string

本文关键字:样式 字符串      更新时间:2023-09-26

我希望我的网站标题每次出现在标题中时都以与其他内容不同的独特字体显示,这是出于品牌推广的原因。为了简单起见,让我们假设我的特殊字体是Courier,我的公司叫SparklePony。因此,像

这样的行
<h1 class="title">SparklePony Board of Directors</h1>

将显示一个标题与SparklePony在Courier和董事会在我的网站默认字体,Arial。(是的,我知道这会很可怕。)

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

我做错了我的字符串替换,或者有一个更好的方式来样式字符串的所有出现?

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

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

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

它可以做一些整理,但这可能是一个很好的起点: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;
};

试试这样做:

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

简洁明了:

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

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

Demo here (fiddle)