加载HTML字符串内容时,字体自适应屏幕问题处理,在创建 WKWebView 时,注入相关的js:

WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *script = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

对于图片处理,只需要给图片一个最大的宽度,也就是屏幕宽度或相对最大宽度,让图片自适应,超过最大宽度,让图片宽度等于最大宽度,其余的情况不做处理,图片高度自适应

 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"
                            "var maxWidth = %f;n"
                            "for(var k in  $img){n"
                            "if($img[k].width> maxWidth){n"
                            " $img[k].style.width = maxWidth;n"
                            "}n"
                            "$img[k].style.height ='auto'n"
                            "}n"
                            "}"
                            "</script>%@"
                            "</body>"
                            "</html>", _maxWidth,string];
    
    [self.webView loadHTMLString:htmlString baseURL:nil];

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/wangkejia/p/15199542.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!