Csharp/C#教程:如何在WebBrowser控件中注入CSS?分享


如何在WebBrowser控件中注入CSS?

据我所知,有一种方法可以将javascript注入DOM。 下面是使用webbrowser控件注入javascript的示例代码:

 HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0]; HtmlElement scriptEl = webBrowser1.Document.CreateElement("script"); IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement; element.text = "function sayHello() { alert('hello') }"; head.AppendChild(scriptEl); webBrowser1.Document.InvokeScript("sayHello"); 

是否有更简单的方法将css注入DOM?

我自己没有尝试过,但由于CSS样式规则可以使用

标签包含在文档中,如下所示:

     

你可以尝试给予:

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

一个去。 您可以在此处找到有关IHTMLStyleElement的更多信息。

编辑

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

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

我写了一个小测试项目,以validation这是否有效。 我通过在MSDN上搜索IHTMLStyleSheet来得到这个最终结果,我在这个页面和这个页面上发生了这个问题 。

上述就是C#学习教程:如何在WebBrowser控件中注入CSS?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/953643.html

(0)
上一篇 2021年11月19日
下一篇 2021年11月19日

精彩推荐