需求:混合應用UIWebView打開html後,UIWebView有左右滾動條,要去掉左右滾動效果;
方法:經過js截獲UIWebView中的html,而後修改html標籤內容;
實例代碼:
服務器端html
- <html><head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
- <title>網曝四川省一考場時鐘慢半小時 老師稱這就是命</title></head<body>網曝四川省一考場時鐘慢半小時 老師稱這就是命</body></html>
這樣顯示的結果網頁的最小寬度會是device-width;但有時候不須要這個寬度,就須要修改width=device-width爲width=myWidth;
客戶端代碼
- - (void)webViewDidFinishLoad:(UIWebView *)webView
- {
-
- NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", webView.frame.size.width];
- [webView stringByEvaluatingJavaScriptFromString:meta];
- }
這樣問題就能夠解決了
新增代碼:
- [webView stringByEvaluatingJavaScriptFromString:
- @"var tagHead =document.documentElement.firstChild;"
- "var tagMeta = document.createElement(\"meta\");"
- "tagMeta.setAttribute(\"http-equiv\", \"Content-Type\");"
- "tagMeta.setAttribute(\"content\", \"text/html; charset=utf-8\");"
- "var tagHeadAdd = tagHead.appendChild(tagMeta);"];
- [webView stringByEvaluatingJavaScriptFromString:
- @"var tagHead =document.documentElement.firstChild;"
- "var tagStyle = document.createElement(\"style\");"
- "tagStyle.setAttribute(\"type\", \"text/css\");"
- "tagStyle.appendChild(document.createTextNode(\"BODY{padding: 20pt 15pt}\"));"
- "var tagHeadAdd = tagHead.appendChild(tagStyle);"];
- [webView stringByEvaluatingJavaScriptFromString:
- @"var script = document.createElement('script');"
- "script.type = 'text/javascript';"
- "script.text = \"function ResizeImages() { "
- "var myimg,oldwidth;"
- "var maxwidth=380;"
- "for(i=0;i <document.images.length;i++){"
- "myimg = document.images[i];"
- "if(myimg.width > maxwidth){"
- "oldwidth = myimg.width;"
- "myimg.width = maxwidth;"
- "myimg.height = myimg.height * (maxwidth/oldwidth);"
- "}"
- "}"
- "}\";"
- "document.getElementsByTagName('head')[0].appendChild(script);"];
-
- [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
其餘html屬性重載和此方法相似; 參考網址: (stringByEvaluatingJavaScriptFromString的使用方法)http://www.uml.org.cn/mobiledev/201108181.asp ( iphone 獲取UIWebView內Html方法)http://blog.csdn.net/diyagoanyhacker/article/details/6564897 (IOS UIWebView引用外部CSS樣式)http://hi.baidu.com/jwq359699768/item/780879e5c98bfb3e4ddcaf22 http://blog.csdn.net/xdonx/article/details/6973521