JavaScript修改CSS变量后内容未正常渲染的原因咨询
Let’s break down exactly what’s going wrong and how to fix it:
The Core Issue
This problem stems from inconsistent quote handling between your initial CSS variable definition and the value you’re setting via JavaScript:
In your original CSS, you wrapped the variable value in double quotes:
:root{ --name: "*"; }When this feeds into
.test::before'scontentproperty, it resolves tocontent: "*";— valid CSS that renders the asterisk correctly.But your JavaScript code sets the variable to an unquoted string:
document.documentElement.style.setProperty("--name", "test");Now the CSS variable
--nameequalstest(no quotes), so thecontentproperty becomescontent: test;. In CSS, unquoted values like this are treated as identifiers (think custom property names or built-in keywords), not plain text content. Sincetestisn’t a valid keyword forcontent, the browser doesn’t render anything — hence the missing asterisk and lack of your desired "test" text.
Simple Fixes
You have two straightforward ways to resolve this:
Option 1: Add Quotes to the JavaScript Value
Escape double quotes in the string you pass to setProperty, so the CSS variable receives a quoted value matching your initial setup:
// Escape quotes to ensure the CSS variable gets wrapped text document.documentElement.style.setProperty("--name", "\"test\"");
Now the variable resolves to "test", so content: var(--name) becomes content: "test"; — which renders exactly as you want.
Option 2: Adjust CSS to Handle Unquoted Values
Modify your CSS to wrap the variable in quotes directly in the content property. You’ll also need to remove quotes from the initial variable value to avoid double-quoting:
:root{ --name: *; } .test::before{ font-size: 13px; // Wrap the variable to force it to be treated as string content content: "\"" var(--name) "\""; }
This works if you want to pass unquoted values from JavaScript, but note that the initial asterisk will render with surrounding quotes. If you don’t want quotes around the text, skip the outer quotes in the content property — just be aware that this only works for values that are valid CSS identifiers (the asterisk isn’t one, so this option is better for plain text like "test").
For your specific use case, Option 1 is the most consistent and straightforward fix.
内容的提问来源于stack exchange,提问作者さかな

