如果纯粹是为了设置文本的样式,那么可能需要使用JavaScript/jQuery。下面是一个快速示例,它将所有“ipsum”实例替换为
<span class="red">ipsum</span>
完整代码:
// Find text in descendents of an element, in reverse document order
// pattern must be a regexp with global flag
//
function findText(element, pattern, callback) {
for (var childi= element.childNodes.length; childi-->0;) {
var child= element.childNodes[childi];
if (child.nodeType==1) {
findText(child, pattern, callback);
} else if (child.nodeType==3) {
var matches= [];
var match;
while (match= pattern.exec(child.data))
matches.push(match);
for (var i= matches.length; i-->0;)
callback.call(window, child, matches[i]);
}
}
}
findText(document.body, /ipsum/g, function(node, match) {
var span= document.createElement(\'span\');
span.className= \'red\';
node.splitText(match.index + 5); // +5 is the length of the string to replace
span.appendChild(node.splitText(match.index));
node.parentNode.insertBefore(span, node.nextSibling);
});
小提琴:
http://jsfiddle.net/QH5nG/5/
替换此处找到的文本代码:
https://stackoverflow.com/questions/1501007/how-can-i-use-jquery-to-style-parts-of-all-instances-of-a-specific-word#answer-1501213