滚动到UIWebView上的文本

我正在开发一个带有最新SDK和XCode 4.2的iOS应用程序。

我想在UIWebview中搜索文本并滚动到找到的第一个文本。

我正在使用本教程查找文本:http: //zaldzbugz.posterous.com/how-to-search-a-string-inside-uiwebview

如何滚动到找到的第一个文本?

我们一步一步走吧。

突出

  1. 在您搜索的文本周围添加span元素。 对于跨度,突出显示颜色设置为跨度的背景。 修改后的HTML字符串将在视图中呈现。

您使用的代码包含以下代码段。

var span = document.createElement("span"); var text = document.createTextNode(value.substr(idx,keyword.length)); span.appendChild(text); span.setAttribute("class","uiWebviewHighlight"); span.style.backgroundColor="black"; span.style.color="white"; 

我们需要一个id到跨度移动。所以添加id如下,

  var span = document.createElement("span"); var text = document.createTextNode(value.substr(idx,keyword.length)); span.appendChild(text); span.setAttribute("id","SEARCH WORD"); span.setAttribute("class","uiWebviewHighlight"); span.style.backgroundColor="black"; span.style.color="white"; 

移至第一次出现。

使用’Webview didload’中的以下javascript移动到第一次出现。

 [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('SEARCH WORD').scrollIntoView()]; 

希望这有用。

看一下您用于突出显示的教程中的最后一条评论。 http://zaldzbugz.posterous.com/how-to-search-a-string-inside-uiwebview

在使用span进行所有操作后,将此代码块添加到UIWebViewSearch.js中

 //old code 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; //new portion of code if (uiWebview_SearchResultCount == 1) { var desiredHeight = span.offsetTop - 140; window.scrollTo(0,desiredHeight); } 

我在iPhone模拟器4.3和5.0上检查了这个解决方案。

您可以滚动到此修改中找到的最顶层文本:

 // >=1 if (uiWebview_SearchResultCount >= 1) { var desiredHeight = span.offsetTop - 140; window.scrollTo(0,desiredHeight); }