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@code { private async Task UpdateThemeColor(string color) { await JSRuntime.InvokeVoidAsync("setCssVar", "--primary-color", color); } }
这样就能把 --primary-color 应用到整个页面(作用于 :root)。如果只想作用于某个元素,把 document.documentElement 换成对应元素引用(见下一条)。
适合局部样式控制,比如卡片背景、按钮悬停色等。
@ref 获取 DOM 元素引用:...@code { private ElementReference cardElement;
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 TaskGetPrimaryColor() { return await JSRuntime.InvokeAsync ("getCssVar", "--primary-color"); }
注意返回值可能为空字符串或带空格,建议调用后做 .Trim() 处理。
避免每个组件都写 JS 调用,可以封装一个 CssVariableService:
Services/CssVariableService.cs):public class CssVariableService
{
private readonly IJSRuntime _jsRuntime;
public CssVariableService(IJSRuntime jsRuntime) => _jsRuntime = jsRuntime;
public ValueTask SetRoot(string property, string value) =>
_jsRuntime.InvokeVoidAsync("setCssVar", pr
operty, value);
public ValueTask GetRoot(string property) =>
_jsRuntime.InvokeAsync("getCssVar", property);
}
Program.cs):builder.Services.AddScoped();
@inject CssVariableService CssVars@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 局部)。