How to get position of an element in UIWebView?

a 夏天 提交于 2019-12-02 20:40:23

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;
}

Ok, i solved using jquery function

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

I gets real x, y values. Thanks.

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!