加載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];
