简体   繁体   English

WebView即时加载css

[英]WebView load css on the fly

I have the following code which loads and html file into a webview 我有以下代码加载和HTML文件到webview

- (void)awakeFromNib{

    NSString *resourcesPath = [[NSBundle mainBundle] resourcePath];
    NSString *htmlPath = [resourcesPath stringByAppendingString:@"/main.html"];
    [[self mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:htmlPath]]];

}

How would i dynamically load a css file (in the most efficient manner) as it does not suit to have the css file link in the html file 我将如何动态加载css文件(以最有效的方式),因为它不适合在html文件中使用css文件链接

You should access the DOM using the Objective-C DOM API and insert the appropriate <link> or <style> element into the DOM. 您应该使用Objective-C DOM API访问DOM,并将适当的<link><style>元素插入DOM。

DOMDocument* domDocument=[webView mainFrameDocument];
DOMElement* styleElement=[domDocument createElement:@"style"];
[styleElement setAttribute:@"type" value:@"text/css"];
DOMText* cssText=[domDocument createTextNode:@"body{font-weight:bold;}"];
[styleElement appendChild:cssText];
DOMElement* headElement=(DOMElement*)[[domDocument getElementsByTagName:@"head"] item:0];
[headElement appendChild:styleElement];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM