<!DOCTYPE html>
<html>
<head>
<title>title</title>
</head>
<body>
<p id="title">this is a test.this is a test</p>
<script>
var str = document.getElementById("test").innerHTML;
var patt1 = /is/gim;
patt1.exec(str);
</script>
</body>
</html>
诸如以上代码,如何能匹配title
文本中的is
关键字,并使之在网页中反色显示。
PS:我想可以找到关键字,然后给关键字的文本对象加入一个CSS 样式
,比如<span class="guanjianzi">is</span>
,但我又不知如何动手。
var el = document.getElementById('title');
el.innerHTML = el.innerHTML.replace(/is/g, '<span class="guanjianzi">is</span>');
找到一个很棒的 jQuery 插件,可以这样进行高亮:$('#title').highlight('is');
Source
從那個插件中找到如下關鍵代碼
jQuery.extend({
highlight: function (node, re, nodeName, className) {
if (node.nodeType === 3) {
var match = node.data.match(re);
if (match) {
var highlight = document.createElement(nodeName || 'span');
highlight.className = className || 'highlight';
var wordNode = node.splitText(match.index);
wordNode.splitText(match[0].length);
var wordClone = wordNode.cloneNode(true);
highlight.appendChild(wordClone);
wordNode.parentNode.replaceChild(highlight, wordNode);
return 1; //skip added node in parent
}
} else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
!/(script|style)/i.test(node.tagName) && // ignore script and style nodes
!(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
for (var i = 0; i < node.childNodes.length; i++) {
i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
}
}
return 0;
}
});
只要這樣調用:jQuery.highlight($("#title"), re, "span", "highlight");
就可以支持正則了。
或者:
jQuery.fn.highlightReg = function(re) {
return this.each(function () {
jQuery.highlight(this, re, "span", "highlight");
});
}
$('#title').highlightReg(/\b(is)\b/i);
https://github.com/bartaz/sandbox.js/blob/master/jquery.highlight.js
var html = $('#title').html();
html = html.replace(/is/g, '<span class="guanjianzi">is</span>');
$('#title').html(html);