问题
For some reason, I need to get the caret vertical position in a content editable UIWebView. As many methods to do that stop caret blinking (for example when creating/removing a hidden node), I use this javascript/Objective-C code:
- (CGRect)caretRect {
NSString *js = @"function f(){ var sel = document.getSelection(); var range = sel.getRangeAt(0).cloneRange(); range.collapse(true); var r =range.getClientRects()[0]; return '{{'+r.left+','+r.top+'},{'+r.width+','+r.height+'}}'; } f();";
NSString *result = [self.webTexteView stringByEvaluatingJavaScriptFromString:[NSString stringWithString:js]];
CGRect rect = CGRectFromString(result);
return rect;
}
Unfortunately, when the caret is on a blank line, this code returns a {0, 0} {0, 0} rect...
Does anybody knows how getting caret rect (at list the vertical position in pixels) in any circumstances, while keeping it blinking? Thanks!
回答1:
This answer fixed this problem for me: https://stackoverflow.com/a/6847328/135712
Basically, you need to insert a new DOM element, get its position, then remove it.
来源:https://stackoverflow.com/questions/24467062/get-caret-rect-in-content-editable-uiwebview-when-its-on-a-blank-line