首页 > 解决方案 > 将外部 css 文件添加到 dom AngleSharp

问题描述

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

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

<!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;
}

标签: anglesharp

解决方案


是的。其实有多种方式。

我想你正在寻找的是:

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();

希望有帮助!


推荐阅读