我认为最直接的方法是使用我遇到的智能jQuery highlight 插件。应用它后,您将能够做您所追求的。下面是一个示例,末尾有一个 live fiddle 的链接:
HTML
<p>Some examples of how to highlight words with the jQuery Highlight plugin. First an example to demonstrate the default behavior and then others to demonstrate how to highlight the words Facebook and Twitter with their own class names. Words will be highlighted anywhere in the DOM, one needs only to be specific on where the script should look for the words. It supports case-sensitivity and other options, like in the case of YouTube.</p>
CSS
p { line-height: 30px; }
span { padding: 4px; }
.highlight { background-color: yellow; }
.facebook { background-color: #3c528f; color: white; }
.twitter { background-color: #1e9ae9; color: white; }
.youtube { background-color: #be0017; color: white; }
高亮插件(需要在jQuery之后和下面JavaScript之前加载)
<script type="text/javascript" src="http://github.com/bartaz/sandbox.js/raw/master/jquery.highlight.js"></script>
JS
// default
$("body p").highlight("default");
// specify class name (not case sensitive)
$("body p").highlight("twitter", { className: 'twitter' });
$("body p").highlight("facebook", { className: 'facebook' });
// specify class name (case sensitive)
$("body p").highlight("YouTube", { className: 'youtube', caseSensitive: true });
在页面底部包含这个JavaScript(在body结束标记之前,这样你就不需要使用下面的函数了:
$(document).ready(function() {
// unnecessary if you load all your scripts at the bottom of your page
});
Fiddle for the win! :)