14

I have UIWebView loaded with html in my iPad Program. By using -webkit-column-width, I divided the html with several columns.

padding: 0px
height: 1024px
-webkit-column-gap: 0px
-webkit-column-width: 768px

How can i get the element position(x, y) in webview? The position is on the screen position, not in the html. So y is in range from 0 to height of webview.

Thanks in advance.

cyberworld
  • 694
  • 7
  • 22
  • Is this not the same as your question at http://stackoverflow.com/questions/7378102/using-css3-columns-how-can-get-element-position/7429994? – chris5marsh Sep 19 '11 at 10:21

3 Answers3

35

Because having to include jQuery just for this sucks:

- (CGRect)positionOfElementWithId:(NSString *)elementID {
    NSString *js = @"function f(){ var r = document.getElementById('%@').getBoundingClientRect(); return '{{'+r.left+','+r.top+'},{'+r.width+','+r.height+'}}'; } f();";
    NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:js, elementID]];
    CGRect rect = CGRectFromString(result);
    return rect;
}
Johan Kool
  • 15,637
  • 8
  • 64
  • 81
2

Ok, i solved using jquery function

var p  = $("tag");
var position = p.position();

I gets real x, y values. Thanks.

cyberworld
  • 694
  • 7
  • 22
1

Here is the swift 4 version of @JohanKools answer https://stackoverflow.com/a/8307454

func positionOfElement(withId elementID: String?) -> CGRect 
{
    let js = "function f(){ var r = document.getElementById('%@').getBoundingClientRect(); return '{{'+r.left+','+r.top+'},{'+r.width+','+r.height+'}}'; } f();"
    let result = webView?.stringByEvaluatingJavaScript(from: String(format: js, elementID))
    let rect: CGRect = CGRectFromString(result!)
    return rect
}