我认为最直接的方法是使用我遇到的智能jQuery 高亮插件。应用它后,您将能够做您所追求的。下面是一个例子,最后有一个现场小提琴的链接:
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; }
Highlight Plugin(需要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
});
为胜利而战!:)