【问题标题】:Scroll to text on UIWebView [closed]滚动到 UIWebView 上的文本 [关闭]
【发布时间】:2012-02-17 08:16:55
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript ios cocoa-touch uiwebview


    【解决方案1】:

    让我们一步一步来。

    突出显示

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

    你使用的代码有以下sn-p。

        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到span来移动。所以添加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()];
    

    希望这有帮助。

    【讨论】:

      【解决方案2】:

      查看您用于突出显示的教程中的最后一条评论。 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 Simulator 4.3 和 5.0 上检查过这个解决方案。

      【讨论】:

      • 如何滚动到最上面找到的文本?
      • 当 uiWebview_SearchResultCount 等于 1 这意味着当前跨度正在突出显示第一次出现的突出显示的文本。
      【解决方案3】:

      您可以滚动到使用此修改找到的最顶部的文本:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-04
        • 2014-08-02
        • 2011-08-15
        相关资源
        最近更新 更多