iOS 修改webView字型

weixin_33762321發表於2018-04-24

五中方案

    UIFont *font = [UIFont systemFontOfSize:12];
    
    //方法一
    NSString *fontColor =@"CCCCFF";
    NSString *htmlString =[NSString stringWithFormat:@"<html> \n"
                        "<head> \n"
                        "<style type=\"text/css\"> \n"
                        "body {font-family: \"%@\"; color: %@;}\n"
                        "</style> \n"
                        "</head> \n"
                        "<body>%@</body> \n"
                        "</html>", font.familyName,fontColor,self.html];
    //方法二
   NSString* htmlString = [NSString stringWithFormat:@"<span style=\"font-family: %@!important; font-size: %i\">%@</span>",
                  font.fontName,
                  (int) font.pointSize,
                  self.html];
    //方法三
    NSString *htmlString = [NSString stringWithFormat:@"<font face='%@' >%@", font.fontName,self.html];
    
   //以上三種方法都需 提起獲取到 html,然後用下面方法載入html
    [self loadHTMLString:htmlString baseURL:DDWebBaseURL];
    
    //方法4 也可以在webview中代理方法中修改  這種方法體驗不好 
    
    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        UIFont *font = [UIFont systemFontOfSize:14];        
         NSString *script = [NSString stringWithFormat:@"document.body.style.fontFamily = '%@'",font.familyName];
        [webView stringByEvaluatingJavaScriptFromString:script]; 
    }

    //通過修改DOM,修改特定節點的樣式
    NSString *script1 = @"document.getElementsByClassName('component-item component-content')[0].getElementsByTagName('p')[0].style.fontSize='30px'";
    NSString *script = @"document.getElementsByClassName('component-item component-content')[0].getElementsByTagName('p')[0].style.fontFamily='DFWaWaW5'";
    NSString *html341 =[webView stringByEvaluatingJavaScriptFromString:script1];
    NSString *html34 =[webView stringByEvaluatingJavaScriptFromString:script];
    
    //方法5 [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust = '200%'"];
    
複製程式碼

在專案中使用webview開啟doc、pdf等檔案時,我採用的是第5種方式,將頁面的字型進行放大

相關文章