加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 17:38:35 所属栏目:百科 来源:网络整理
导读:据我所知,有一种注入到DOM的方法.以下是使用webbrowser控件注入 javascript的示例代码: HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");IHTMLScriptEleme
据我所知,有一种注入到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样式规则可以包含在使用< style>标签如:
<html>
<head>
<style type="text/css">
    h1 {color:red}
    p {color:blue}
</style>
</head>

你可以尝试给:

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 here上找到更多信息.

编辑

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

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.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读