anglesharp - 将外部 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;
}
解决方案
是的。其实有多种方式。
我想你正在寻找的是:
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();
希望有帮助!
推荐阅读
- java - String 类的长度成员是整数常量吗?
- python - 电子邮件无法在 Python 中发送。[Errno 61] 发生连接被拒绝错误
- assembly - 从Assembly中的字符串访问字符
- django - 有没有一种快速的方法来获取当前页面 url 的结尾?姜戈
- mysql - 是什么导致这个联合所有功能停止工作?
- javascript - 如何存储 JWT 以及如何在 cookie 中使用它
- perl - 将字符串作为数组传递给子程序并返回特定字符的计数
- r - 无法选择正确的 css 元素以使用 rvest 进行抓取
- c - 如何将一系列整数分配给struct中的指针var
- r - mapply 中的函数调用返回列表而不是数据框