方法一
处理HTMLString的方法:
NSString *htmls = [NSString stringWithFormat:@"<html> \n"
"<head> \n"
"<style type=\"text/css\"> \n"
"body {font-size:15px;}\n"
"</style> \n"
"</head> \n"
"<body>"
"<script type='text/javascript'>"
"window.onload = function(){\n"
"var $img = document.getElementsByTagName('img');\n"
"for(var p in $img){\n"
" $img[p].style.width = '100%%';\n"
"$img[p].style.height ='auto'\n"
"}\n"
"}"
"</script>%@"
"</body>"
"</html>",htmlString];
[self.webView loadHTMLString:htmlString baseURL:nil];
处理HTMLString的原理:
原理就是用一个for循环,拿到所有的图片,对每个图片都处理一次,让图片的宽为100%,就是按照屏幕宽度自适应;让图片的高atuo,自动适应。文字的字体大小,可以去改font-size:15px,这里我用的是15px。根据自己的具体需求去改吧。
方法二
[webView stringByEvaluatingJavaScriptFromString:
@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function ResizeImages() { "
"var myimg,oldwidth;"
"var maxwidth=300;" //缩放系数 改变参数控制图片缩放大小
"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();"];
方法三