添加外部 css 文件到 dom AngleSharp

Add external css file to dom AngleSharp

我有一个外部 CSS 文件,该文件未在 html 文件中引用。是否可以添加此 CSS 文件并通过 AngleSharp 将样式应用到 html?

我想到的另一种解决方法是在将 CSS 解析为 DOM 之前在 html 中插入对 CSS 的引用,但我想知道 AngleSharp 是否提供了我实施 "workaround" 之前的初始问题。非常感谢!

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>Test Doc</title>

</head>

<body>
  <div id="styleme">
    Hello
  </div>

</body>
</html>

通知没有 css 链接。

和外部 css 文件:

#styleme {
  color:blue;
  background-color: gray;
}

是的。其实有多种方式。

我猜你要找的是:

var config = Configuration.Default.WithCss();
// note: ideally load your document from a URL directly if applicable
var document = await BrowsingContext.New(config)
    .OpenAsync(res => res.Content(@"<!doctype html>
<html lang=en>
<head>
<meta charset='utf-8'>
<title>Test Doc</title>
</head>
<body>
<div id=styleme>
Hello
</div>
</body>
</html>"));
var style = document.CreateElement<IHtmlStyleElement>();
// note: if you have the CSS from a URL; choose IHtmlLinkElement instead
style.TextContent = @"#styleme { color:blue; background-color: gray; }";
document.Head.AppendChild(style);
// note: using LINQPad here; you may want to store the style somewhere
document.DefaultView.GetComputedStyle(document.QuerySelector("#styleme")).Dump();

希望对您有所帮助!