第一种:发现小于屏幕宽度的图片并不会被拉的屏幕一样宽
WKUserContentController *userContentController = [[WKUserContentController alloc] init];
WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
// 自适应屏幕宽度js
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
// 添加自适应屏幕宽度js调用的方法
[userContentController addUserScript:wkUserScript];
wkWebConfig.userContentController= userContentController;
WKWebView*webview =[[WKWebViewalloc]initWithFrame:self.view.boundsconfiguration:wkWebConfig];
webview.navigationDelegate =self;
[webviewloadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://app.elcst.com/index.php?ctl=goods&act=goods_body&goods_id=1600"]]];//https://baidu.com
[self.viewaddSubview:webview];
第二种:
实现这个WKNavigationDelegate 代理方法,解决了第一种方法存在的不足
- (void)webView:(WKWebView*)webView didFinishNavigation:(null_unspecifiedWKNavigation*)navigation{
[webViewevaluateJavaScript:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function ResizeImages() { "
"var myimg,oldwidth;"
"var maxwidth = 1000.0;" // UIWebView中显示的图片宽度
"for(i=0;i
"myimg = document.images[i];"
"oldwidth = myimg.width;"
"myimg.width = maxwidth;"
"}"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);ResizeImages();" completionHandler:nil];
}
网友评论