将HTML元素放在UIWebView中的位置

时间:2012-06-14 10:20:27

标签: javascript iphone objective-c ios uiwebview

我试图在UIWebView视图中获得最顶层的元素。

我一直在尝试

NSString *topElementInView = [self.webView stringByEvaluatingJavaScriptFromString: @"document.elementFromPoint(0, 0);"];

但它没有返回任何东西。 WebView完成加载后运行代码。

2 个答案:

答案 0 :(得分:0)

这是一个示例ViewController.m:

#import "ViewController.h"

@interface ViewController () <UIWebViewDelegate>

@property (nonatomic) UIWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];


    NSString *HTML = @"<!DOCTYPE html> <html> <head> <title></title> <meta http-equiv=\"content-type\" content=\"text/html; charset=“utf-8\"> <!-- Internal CSS --> <style type=\"text/css\"> </style> <!-- Extrernal CSS --> <link rel=\"stylesheet\" href=\"css/normalize.css\"> <!-- jQuery  --> <script src=\"http://code.jquery.com/jquery.min.js\" type=\"text/javascript\"></script> <!-- Internal JavaScripts --> <script type=\"text/javascript\"> </script> </head> <body> <a href=\"https://www.google.com/images/srpr/logo11w.png\"> <img src=\"https://www.google.com/images/srpr/logo11w.png\" alt=\"google\"> <p>This is a Google image.</p> </a> </body> </html>";

    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [self.view addSubview:self.webView];

    self.webView.delegate = self;

    [self.webView loadHTMLString:HTML baseURL:nil];

}


- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *htmlInner = [self.webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];
    NSLog(@"inner\n%@",htmlInner);

    NSString *htmlOuter = [self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML"];
    NSLog(@"outer\n%@",htmlOuter);
}

答案 1 :(得分:-6)

- (void)viewDidLoad {   
 js=dic;
//NSString *js;  (.h)
[self.myWebView loadHTMLString:js baseURL:nil];
}

//委托

- (void)webViewDidFinishLoad:(UIWebView *)webView {
[myWebView stringByEvaluatingJavaScriptFromString:js];
}