【发布时间】:2015-12-19 09:10:12
【问题描述】:
我正在尝试在我的一个网页屏幕上添加一个搜索栏,以便搜索并突出显示所有搜索到的关键字。通过我在此处找到的堆栈溢出示例,我可以搜索文本中硬编码的任何文本,但我有一个文件被读入窗口,我希望能够以相同的方式搜索和突出显示。有人可以帮助我吗?
Javascript
var MyApp_SearchResultCount;
var currSelected;
function MyApp_HighlightAllOccurencesOfStringForElement(element,keyword) {
MyApp_SearchResultCount = 0;
currSelected = -1;
if (element) {
if (element.nodeType == 3) { // Text node
while (true) {
var value = element.nodeValue; // Search for keyword in text node
var idx = value.toLowerCase().indexOf(keyword);
if (idx < 0) break; // not found, abort
var span = document.createElement("span");
var text = document.createTextNode(value.substr(idx,keyword.length));
span.appendChild(text);
span.setAttribute("class","MyAppHighlight");
span.style.backgroundColor="yellow";
span.style.color="black";
text = document.createTextNode(value.substr(idx+keyword.length));
element.deleteData(idx, value.length - idx);
var next = element.nextSibling;
element.parentNode.insertBefore(span, next);
element.parentNode.insertBefore(text, next);
element = text;
MyApp_SearchResultCount++; // update the counter
}
} else if (element.nodeType == 1) { // Element node
if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
for (var i=element.childNodes.length-1; i>=0; i--) {
MyApp_HighlightAllOccurencesOfStringForElement(element.childNodes[i],keyword);
}
}
}
}
}
function goNext(){
jump(1);
}
function goPrev(){
jump(-1);
}
function jump(howHigh){
prevSelected = currSelected;
currSelected = currSelected + howHigh;
if (currSelected < 0){
currSelected = MyApp_SearchResultCount + currSelected;
}
if (currSelected >= MyApp_SearchResultCount){
currSelected = currSelected - MyApp_SearchResultCount;
}
prevEl = document.getElementsByClassName("MyAppHighlight")[prevSelected];
if (prevEl){
prevEl.style.backgroundColor="yellow";
}
el = document.getElementsByClassName("MyAppHighlight")[currSelected];
el.style.backgroundColor="green";
el.scrollIntoView(true); //thanks techfoobar
}
HTML
<div id="divSection" class="divSection" onclick="selectAll(this)">
<%=bean.getValue("configText")%>
<p> BlahBlahBlahBlahBlahBlahBlahBlahBlahBlahBlahBlah </p>
</div>
请看这个例子http://jsfiddle.net/catherinepaul01/eb344g2c/2/
注意。如果有人知道你可以使用dojo做到这一点,那就更好了!!
【问题讨论】:
标签: javascript search find highlight