mar*_*man 5 css c# mshtml microsoft.mshtml
我试图在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>
Run Code Online (Sandbox Code Playgroud)
并且在webbrowser控件的LoadComplete事件中分配css的方式是:
mshtml.IHTMLStyleSheet styleSheet = Document.createStyleSheet(string.Empty, 0);
styleSheet.cssText = @".backgroundImageDivsClass{display:none;}";
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用,因为它没有隐藏div.有人请告诉我一些我缺少的东西.
这是我根据你的描述使用的方法,效果很好。
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;}";
}
Run Code Online (Sandbox Code Playgroud)