美文网首页
UIWebView loadHtmlString图片自适应

UIWebView loadHtmlString图片自适应

作者: 多来猫 | 来源:发表于2017-11-13 16:43 被阅读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];
    

    问题完美解决

    相关文章

      网友评论

          本文标题:UIWebView loadHtmlString图片自适应

          本文链接:https://www.haomeiwen.com/subject/hbbzmxtx.html