Blazor中C#需通过JSRuntime调用JavaScript操作CSS变量,核心是set/get style.setProperty与getComputedStyle;全局用document.documentElement,局部用ElementReference;须带--前缀,可封装为服务复用。

Blazor 中可以用 C# 动态设置或读取 CSS 变量(Custom Properties),核心是通过 JSRuntime 调用 JavaScript 操作 style.setProperty 或 getComputedStyle,因为 C# 无法直接访问 CSSOM。不过 Blazor 提供了简洁的互操作方式,配合少量 JS 就能高效完成。
最常用场景是根据状态动态更新主题色、尺寸等。需要两步:定义 JS 函数 + C# 调用。
wwwroot/js/site.js(或 _Host.cshtml 中)添加:window.setCssVar = (property, value) => {
document.documentElement.style.setProperty(property, value);
};.razor)中注入并调用:@inject IJSRuntime JSRuntime
<p>@code {
private async Task UpdateThemeColor(string color) {
await JSRuntime.InvokeVoidAsync("setCssVar", "--primary-color", color);
}
}这样就能把 --primary-color 应用到整个页面(作用于 :root)。如果只想作用于某个元素,把 document.documentElement 换成对应元素引用(见下一条)。
适合局部样式控制,比如卡片背景、按钮悬停色等。
立即学习“前端免费学习笔记(深入)”;
@ref 获取 DOM 元素引用:<div @ref="cardElement" class="card">...</div>
<p>@code {
private ElementReference cardElement;</p><p>private async Task SetCardBg(string hex) {
await JSRuntime.InvokeVoidAsync("setElementCssVar", cardElement, "--card-bg", hex);
}
}window.setElementCssVar = (element, property, value) => {
element.style.setProperty(property, value);
};适用于响应式逻辑判断,比如根据主题色自动切换文字对比度。
window.getCssVar = (property) => {
return getComputedStyle(document.documentElement).getPropertyValue(property).trim();
};private async Task<string> GetPrimaryColor() {
return await JSRuntime.InvokeAsync<string>("getCssVar", "--primary-color");
}注意返回值可能为空字符串或带空格,建议调用后做 .Trim() 处理。
避免每个组件都写 JS 调用,可以封装一个 CssVariableService:
Services/CssVariableService.cs):public class CssVariableService
{
private readonly IJSRuntime _jsRuntime;
<p>public CssVariableService(IJSRuntime jsRuntime) => _jsRuntime = jsRuntime;</p><p>public ValueTask SetRoot(string property, string value) =>
_jsRuntime.InvokeVoidAsync("setCssVar", property, value);</p><p>public ValueTask<string> GetRoot(string property) =>
_jsRuntime.InvokeAsync<string>("getCssVar", property);
}Program.cs):builder.Services.AddScoped<CssVariableService>();
@inject CssVariableService CssVars
<p>@code {
private async Task ToggleDarkMode() {
var current = await CssVars.GetRoot("--bg-color");
await CssVars.SetRoot("--bg-color", current == "#1a1a1a" ? "#ffffff" : "#1a1a1a");
}
}基本上就这些。关键点在于:C# 不直接操作样式表,而是靠 JS 桥接;变量名必须带两个短横线(--my-var);作用域决定影响范围(:root 全局,元素 style 局部)。
以上就是Blazor 怎么用 C# 操作 CSS 变量的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号