WebView 动态加载 css [英] WebView load css on the fly
本文介绍了WebView 动态加载 css的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码将 html 文件加载到 webview 中
I have the following code which loads and html file into a webview
- (void)awakeFromNib{
NSString *resourcesPath = [[NSBundle mainBundle] resourcePath];
NSString *htmlPath = [resourcesPath stringByAppendingString:@"/main.html"];
[[self mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:htmlPath]]];
}
我将如何动态加载 css 文件(以最有效的方式),因为它不适合在 html 文件中包含 css 文件链接
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
推荐答案
您应该使用 Objective-C DOM API 访问 DOM 并插入适当的 style> 或
元素进入 DOM.
You should access the DOM using the Objective-C DOM API and insert the appropriate <link>
or <style>
element into the 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];
这篇关于WebView 动态加载 css的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文