Scroll to text on UIWebView [closed]

谁都会走 提交于 2019-12-22 17:41:22

问题


I'm developing an iOS application with latest SDK and XCode 4.2.

I want to search a text in a UIWebview and scroll to the first text found.

I'm using this tutorial to find text: http://zaldzbugz.posterous.com/how-to-search-a-string-inside-uiwebview

How can I scroll to first text found?


回答1:


Let's go step by step.

Highlight

  1. A span element is added around the text you search for. For the span, highlight color is set as span's background. The modified HTML string is rendered in the view.

The code you used has the following snippet.

    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";

We need to a id to the span to move.So add id as follows,

      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";

Moving to the First occurrence.

Use the following javascript in 'Webview didload' to move to the first occurence.

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

Hope this is helpful.




回答2:


Take a look at the last comment from tutorial you've used for highlighting. http://zaldzbugz.posterous.com/how-to-search-a-string-inside-uiwebview

Add this block of code into UIWebViewSearch.js after all manipulations with span

//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);
    }

I've checked this solution on iPhone Simulator 4.3 and 5.0.




回答3:


You can scroll to the top most text found with this modification:

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


来源:https://stackoverflow.com/questions/9324927/scroll-to-text-on-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!