c# – 如何在WebBrowser控件中注入CSS?

前端之家收集整理的这篇文章主要介绍了c# – 如何在WebBrowser控件中注入CSS?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
据我所知,有一种注入到DOM的方法.以下是使用webbrowser控件注入 javascript的示例代码
  1. HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
  2. HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
  3. IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
  4. element.text = "function sayHello() { alert('hello') }";
  5. head.AppendChild(scriptEl);
  6. webBrowser1.Document.InvokeScript("sayHello");

有没有更简单的方式将CSS注入DOM?

解决方法

我没有尝试这个,但CSS样式规则可以包含在使用< style>标签如:
  1. <html>
  2. <head>
  3. <style type="text/css">
  4. h1 {color:red}
  5. p {color:blue}
  6. </style>
  7. </head>

你可以尝试给:

  1. HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
  2. HtmlElement styleEl = webBrowser1.Document.CreateElement("style");
  3. IHTMLStyleElement element = (IHTMLStyleElement)styleEl.DomElement;
  4. IHTMLStyleSheetElement styleSheet = element.styleSheet;
  5. styleSheet.cssText = @"h1 { color: red }";
  6. head.AppendChild(styleEl);

一路走来您可以在IHTMLStyleElement here上找到更多信息.

编辑

似乎答案比我原来想的要简单得多:

  1. using mshtml;
  2.  
  3. IHTMLDocument2 doc = (webBrowser1.Document.DomDocument) as IHTMLDocument2;
  4. // The first parameter is the url,the second is the index of the added style sheet.
  5. IHTMLStyleSheet ss = doc.createStyleSheet("",0);
  6.  
  7. // Now that you have the style sheet you have a few options:
  8. // 1. You can just set the content as text.
  9. ss.cssText = @"h1 { color: blue; }";
  10. // 2. You can add/remove style rules.
  11. int index = ss.addRule("h1","color: red;");
  12. ss.removeRule(index);
  13. // You can even walk over the rules using "ss.rules" and modify them.

我写了一个小的测试项目,以验证这是否有效.我通过在MSDN上搜索IHTMLStyleSheet,在this page,this pagethis one发生了这个最终结果.

猜你在找的C#相关文章