【问题标题】:find y coordinate for cursor position in div in UIWebView在 UIWebView 的 div 中查找光标位置的 y 坐标
【发布时间】:2012-06-22 23:20:48
【问题描述】:

我有一个带有一些基本 html 的 UIWebView,它可以作为一个简单的编辑器。

// in initWithFrame: of UIView subclass.
_editorHTML = [@"<!doctype html>"
                   "<html>"
                   "<head>"
                   "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">"
                   "<style type=\"text/css\">"
                   "#content { font-family:Arial, Helvetica, sans-serif; font-size:1em; } "
                   "</style>"
                   "<script type=\"text/javascript\">"
                   "function load()"
                   "{"
                   "    window.location.href = 'ready://' + document.body.offsetHeight;"
                   "}"
                   "</script>"
                   "</head>"
                   "<body id=\"bodyDiv\" onload=\"load()\">"
                   "<div id=\"content\" contenteditable=\"true\">%@</div>"
                   "</body>"
                   "</html>" retain];

_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
_webView.delegate = self;
_webView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
_webView.scrollView.bounces = NO;
[_webView loadHTMLString:[NSString stringWithFormat:_editorHTML, @""] baseURL:[NSURL fileURLWithPath:directory]];

- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *url = [request URL];
    if (navigationType == UIWebViewNavigationTypeOther) {
        if ([[url scheme] isEqualToString:@"ready"]) {

            int height = (int)_webView.frame.size.height;
            [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('content').style.minHeight = '%dpx'", height - WEBVIEW_DIVHEIGHT_OFFSET]];

            return NO;
        }
    }
    return YES;
}

那么,如何确定我的 div 中的光标位置,以便我可以更新我的 scrollView 以确保内容在 UIKeyboard 上方可见,从而不必让用户手动滚动以保持文本可见?

【问题讨论】:

    标签: javascript objective-c ios uiwebview


    【解决方案1】:

    此解决方案是公认答案的演变。修复了 WebKit 中的 newLine 问题。

    function getCaretClientPosition() {
        var x = 0, y = 0;
        var sel = window.getSelection();
        if (sel.rangeCount) {
    
            var range = sel.getRangeAt(0);
            var needsToWorkAroundNewlineBug = (range.startContainer.nodeName.toLowerCase() == 'p'
                                               && range.startOffset == 0);
    
            if (needsToWorkAroundNewlineBug) {
                x = range.startContainer.offsetLeft;
                y = range.startContainer.offsetTop;
            } else {
                if (range.getClientRects) {
                    var rects = range.getClientRects();
                    if (rects.length > 0) {
                        x = rects[0].left;
                        y = rects[0].top;
                    }
                }
            }
        }
        return { x: x, y: y };
    }
    

    【讨论】:

      【解决方案2】:

      @timdown 有趣的是,您的脚本总是返回 0,0 作为行首。不过,来自 [question]: Coordinates of selected text in browser page 的脚本确实返回了正确的 Y 值。

      为了方便搜索,在此重复:

      function getSelectionCoords() {
          var sel = document.selection, range;
          var x = 0, y = 0;
          if (sel) {
              if (sel.type != "Control") {
                  range = sel.createRange();
                  range.collapse(true);
                  x = range.boundingLeft;
                  y = range.boundingTop;
              }
          } else if (window.getSelection) {
              sel = window.getSelection();
              if (sel.rangeCount) {
                  range = sel.getRangeAt(0).cloneRange();
                  if (range.getClientRects) {
                      range.collapse(true);
                      var rect = range.getClientRects()[0];
                      x = rect.left;
                      y = rect.top;
                  }
              }
          }
          return { x: x, y: y };
      }
      

      【讨论】:

      • 在我的测试中,此处链接的不同问题的答案确实解决了问题,但此处重复的代码片段不。诀窍是添加一个 DOM 元素然后获取它的位置,看看这里的代码:stackoverflow.com/a/6847328/135712
      【解决方案3】:

      您可以从选择中获取所选范围并使用其getClientRects() 方法。

      现场演示:http://jsfiddle.net/timdown/xMEjD/

      代码:

      function getCaretClientPosition() {
          var x = 0, y = 0;
          var sel = window.getSelection();
          if (sel.rangeCount) {
              var range = sel.getRangeAt(0);
              if (range.getClientRects) {
                  var rects = range.getClientRects();
                  if (rects.length > 0) {
                      x = rects[0].left;
                      y = rects[0].top;
                  }
              }
          }
          return { x: x, y: y };
      }
      

      【讨论】:

      • @developerdoug:是的。这是你想要的吗?
      • @IvorySantos:在某些浏览器中可能会这样做,但在 Firefox 中不会,因为 window.getSelection() 返回的 Selection 与文本区域和输入中的选择之间没有任何关联。
      • @IvorySantos:事实上,在我尝试过的任何浏览器中,它都不适用于 textareas。
      • 这仅在您按回车时有文本时才有效。如果您将光标移动到行尾并按回车键创建一些返回,则它不会显示准确的值。
      • 当我在新行之后输入第一个字母时,它返回错误的位置( (x,y) = (0,0) )。 (在 iOS 中返回键之后)。有什么想法吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多