function setWordHighlight (word) {
var doc = document,
df = doc.createDocumentFragment(),
span = doc.createElement('span'),
texts = doc.evaluate('descendant::text()[normalize-space(.)]', doc.body, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
span.className = 'high-light';
span.appendChild(doc.createTextNode(word));
for (var i = 0, l = texts.snapshotLength, stringsLength, textNode; i < l; ++i) {
textNode = texts.snapshotItem(i);
strings = textNode.data.split(word);
stringsLength = strings.length;
if (stringsLength > 1) {
df.appendChild(doc.createTextNode(strings[0]));
for (var j = 1; j < stringsLength; ++j) {
df.appendChild(span.cloneNode(true));
df.appendChild(doc.createTextNode(strings[j]));
}
textNode.parentNode.replaceChild(df, textNode);
}
}
}
setWordHighlight('test');
css:
.high-light { color: black; background-color: yellow; font-weight: bold; }
http://jsfiddle.net/3F4Wa/
http://toro.2ch.net/test/read.cgi/hp/1386098775/898
0 件のコメント:
コメントを投稿