Scroll to text on UIWebView [closed]

2019-05-20 01:47发布

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?

3条回答
Rolldiameter
2楼-- · 2019-05-20 02:19

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楼-- · 2019-05-20 02:21

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.

查看更多
相关推荐>>
4楼-- · 2019-05-20 02:32

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);
}
查看更多
登录 后发表回答