5

我正在尝试在 C# WebBrowser 控件(WPF 不是 WinForm)中加载一个网页。除了其他内容,页面还有一个图像旋转器,它动态创建两个具有相同类的 div 以利用图像旋转。在LoadComplete eventWebBrowser 控件中,我附加了一个样式表来隐藏两个 div。页面加载时动态创建的两个 div 如下:

<div class="backgroundImageDivsClass" style="
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0px; 
    left: 0px;
    padding: 0px;
    margin: 0px;
    z-index: -9999;
    opacity: 1;
    background-image: url("data/767/Course/9214/1000000001_474030834.jpg"); 
    background-position: left top;
    background-size: 100% 100%;
    background-repeat: no-repeat;
"></div>
<div class="backgroundImageDivsClass"></div>

在 webbrowser 控件的 LoadComplete 事件中分配 css 的方式是:

mshtml.IHTMLStyleSheet styleSheet = Document.createStyleSheet(string.Empty, 0);
styleSheet.cssText = @".backgroundImageDivsClass{display:none;}";

但这似乎不起作用,因为它没有隐藏 div。任何人都请给我一些想法,我错过了什么。

4

3 回答 3

3

这是我根据您的描述使用的方法,效果很好。

   public MainForm()
   {
        InitializeComponent();

        webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
        var text = @"<html>
                        <body>
                            <div class=""backgroundImageDivsClass"">
                               <span> hello everyone!</span>
                            </div>
                        </body>
                     </html>";

        webBrowser.DocumentText = text;
    }

    void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        var doc = webBrowser.Document.DomDocument as IHTMLDocument2;
        var styleSheet = doc.createStyleSheet(string.Empty, 0);

        var ruleIndex = styleSheet.addRule(".backgroundImageDivsClass", "display:none", 0);//index can be used to remove the rule

        //styleSheet.cssText = @".backgroundImageDivsClass{display:none;}";
    }
于 2015-01-16T08:37:11.457 回答
2
styleSheet.cssText = @".backgroundImageDivsClass{display:none !important;}";

是我的建议。它将强制覆盖任何其他试图设置显示属性的东西。(就像图像旋转器控件)因为任何 !important 标记都是由 DOM 最后应用的

如果这不起作用,请进一步提供帮助..

使用 Firefox 中的 firebug 插件,确定哪些 CSS 属性动态应用于您的 Div。

您可以实时编辑萤火虫渲染的 CSS,直到找到可行的解决方案,然后将其合并到您的解决方案中。

这篇文章很好地补充了我的建议: http ://www.smashingmagazine.com/2010/11/02/the-important-css-declaration-how-and-when-to-use-it/

于 2015-01-16T14:12:59.053 回答
1

我相信问题在于您在 Document 而不是 Document.DomDocument 上使用 createStyleSheet 方法。这里的答案可能是一个有用的参考。

此外,您可以在此处阅读createStyleSheet 不再受支持。从 Internet Explorer 11 开始,您应该使用document.createElement('style')

于 2015-01-19T20:27:22.023 回答