<html>
<head></head>
<body>
<h1>Test Img howtoautofitwebview</h1>
<imgsrc="http://pic.nipic.com/2007-12-15/2007121519169400_2.jpg"></img>
<h2>Another image</h2>
<imgsrc="http://www.zg2sc.cn/upfile/pic/2014/05/14/5f80fc3a258940998f921953269d1960141058011295091_163227633232_2.jpg"></img>
<h2>Third image</h2>
<imgsrc="http://www.jydoc.com/uploads/jydoc/p35501/20091292046379677801.jpg"></img>
</body>
</html>
以上为网页中带有三张图片代码。这三张图片的宽度已经超过iPhone的屏幕宽度,那么我们怎么才能让网页的图片在iPhone中自适应呢。这时候,我们可以使用UIWebView控件加载网页,通过原生API改变网页的CSS,最后达到图片宽度自适应。具体代码如下:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *js = @"function imgAutoFit() { \
var imgs = document.getElementsByTagName('img'); \
for (var i = 0; i < imgs.length; ++i) {\
var img = imgs[i]; \
img.style.maxWidth = %f; \
} \
}";
js = [NSStringstringWithFormat:js, [UIScreen mainScreen].bounds.size.width - 20];
[webViewstringByEvaluatingJavaScriptFromString:js];
[webViewstringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];
}