当我们使用webview加载html时,如果html的内容包含图片,有时会显示特别大,那么就需要我们进行自适应,在webview加载结束的代理方法里面添加以下代码则可以解决:
NSString *js=@“var script = document.createElement(‘script’);”
“script.type = ‘text/javascript’;”
"script.text = “function ResizeImages() { "
“var myimg,oldwidth;”
“var maxwidth = %f;”
“for(i=0;i <document.images.length;i++){”
“myimg = document.images[i];”
“if(myimg.width > maxwidth){”
“oldwidth = myimg.width;”
“myimg.width = %f;”
“}”
“}”
“}”;”
“document.getElementsByTagName(‘head’)[0].appendChild(script);”;
js=[NSString stringWithFormat:js,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.width-15];
[webView stringByEvaluatingJavaScriptFromString:js];
[webView stringByEvaluatingJavaScriptFromString:@“ResizeImages();”];
再使用以下方法可以获取webview的最终内容高度
//获取到webview的高度
CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@“document.body.offsetHeight”] floatValue];
获取html内容的标题
NSString *htmlTitle = @“document.title”;
NSString *titleHtmlInfo = [webView stringByEvaluatingJavaScriptFromString:htmlTitle];
注意:都是在webview加载结束的代理方法下使用才有效
- (void)webViewDidFinishLoad:(UIWebView *)webView