【问题标题】:How to get position of an element in UIWebView?如何获取 UIWebView 中元素的位置?
【发布时间】:2011-09-13 03:28:28
【问题描述】:

我在我的 iPad 程序中加载了带有 html 的 UIWebView。通过使用-webkit-column-width,我将html分成了几列。

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

如何在 webview 中获取元素位置(x,y)?该位置在屏幕位置上,而不是在 html 中。所以 y 的范围是从 0 到 webview 的高度。

提前致谢。

【问题讨论】:

标签: javascript html ios ipad uiwebview


【解决方案1】:

因为仅仅为了这个而必须包含 jQuery 很糟糕:

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

【讨论】:

  • 如何使用 document.getElementByTagName 做同样的事情?
  • 这太棒了!有没有设置boundingClientRect的函数?
【解决方案2】:

好的,我用jquery函数解决了

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

我得到真正的 x,y 值。谢谢。

【讨论】:

  • 如何从位置 var 获取 x, y?
【解决方案3】:

这里是@JohanKools 的swift 4 版本回答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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    相关资源
    最近更新 更多