使用JavaScript更新CSS变量时--basec变量未生效的问题排查
Hey there, let's dig into why your basec variable isn't updating the image background and span color—this is a super common mismatch issue!
The Root Cause: Mismatched Variable Names
Let's break down where the disconnect happens:
- In your HTML, the color input has a
nameattribute set tobase:<input type="color" name="base" id="base" value="#ffe591"> - In your CSS, you've defined the variable as
--basecin the:rootselector::root { --spacing: 10px; --blur: 1px; --basec: #ffe591; } - Your JavaScript uses the input's
nameto target the CSS variable:document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
So when the color input changes, your JS is trying to update a variable called --base (from the input's name="base"), but your CSS is referencing --basec—they don't match! That's why the image background and span color never change.
Quick Fixes (Pick One)
You just need to align the names across all three files:
Option 1: Update the HTML Input's Name
Change the color input's name to basec to match your CSS variable:
<input type="color" name="basec" id="base" value="#ffe591">
Option 2: Update the CSS Variable Name
Rename the CSS variable to --base to match the input's name, and update all references too:
:root { --spacing: 10px; --blur: 1px; --base: #ffe591; } img { padding: var(--spacing); filter: blur(var(--blur)); background: var(--base); } .h1 { color: var(--base); }
Why the Other Variables Worked
Your spacing and blur inputs have name attributes that exactly match their corresponding CSS variables (--spacing and --blur), so the JS can target them correctly—no mismatch there!
Once you fix the name alignment, your base color should update perfectly when you pick a new color.
内容的提问来源于stack exchange,提问作者Diksha

