在UIWebView中找到div中光标位置的y坐标

时间:2012-06-20 18:39:53

标签: javascript objective-c ios uiwebview

我有一个带有一些基本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上方可见,从而不必让用户手动滚动以保持文本在视图中?

3 个答案:

答案 0 :(得分:8)

您可以从选择中获取所选范围并使用其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 };
}

答案 1 :(得分:5)

@timdown有趣的是,你的脚本总是在行的开头返回0,0。 [问题]: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 };
}

答案 2 :(得分: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 };
}