UIWebView loadHtmlString图片自适应

2017-11-13  本文已影响0人  多来猫

使用UIWebView loadHtmlString的时候超宽图片会超出webview的宽度,网上查解决方案如下:

NSString *htmlString = [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>",model.details];

// webView直接加载HTMLString
[self.webView loadHTMLString:htmlString baseURL:nil];

发现使用后超宽的图片确实变成自适应宽度了,可新的问题是原来的小图片被拉伸到与屏幕同宽,改为

NSString *htmlFormatter = @"<html> \n"
"<head> \n"
"<style type=\"text/css\"> \n"
"body {font-size:15px;}\n"
"img {max-width:100%%;height:auto;}\n"
"</style> \n"
"</head> \n"
"<body>"
"%@"
"</body>"
"</html>";
NSString *htmlString = [NSString stringWithFormat:htmlFormatter, self.data.detail];
[self.webView loadHTMLString:htmlString baseURL:nil];

问题完美解决

上一篇 下一篇

猜你喜欢

热点阅读