Javascript 为什么当我更改第二个CSS变量时,第一个CSS变量会重置?自定义颜色主题

Javascript 为什么当我更改第二个CSS变量时,第一个CSS变量会重置?自定义颜色主题,javascript,html,css,css-variables,setattribute,Javascript,Html,Css,Css Variables,Setattribute,目的是制作一个自定义站点颜色主题。问题是当我更改第二个CSS变量时,它首先重置为默认值 var mainColor=document.getElementById(“主颜色”); var secondColor=document.getElementById(“第二种颜色”); 函数颜色(CSS变量,输入值){ 返回CSSVVariable+“:”+inputValue } mainColor.addEventListener('input',function()){ document.d

目的是制作一个自定义站点颜色主题。问题是当我更改第二个CSS变量时,它首先重置为默认值

var mainColor=document.getElementById(“主颜色”);
var secondColor=document.getElementById(“第二种颜色”);
函数颜色(CSS变量,输入值){
返回CSSVVariable+“:”+inputValue
}
mainColor.addEventListener('input',function()){
document.documentElement.setAttribute(“style”,color(--main color,this.value))
})
secondColor.addEventListener('input',function(){
document.documentElement.setAttribute(“style”,color(--second color,this.value))
})
:根目录{
--主色:黑色;
--第二种颜色:白烟;
--主字号:16px;
颜色:var(--主色);
字体大小:var(--主字体大小);
}

问题在于,您正在设置“样式”属性,以便每次重写之前的所有内联样式

您需要使用
setProperty

var mainColor=document.getElementById(“主颜色”);
var secondColor=document.getElementById(“第二种颜色”);
函数颜色(CSS变量,输入值){
返回CSSVVariable+“:”+inputValue
}
mainColor.addEventListener('input',function()){
document.documentElement.style.setProperty(“--main color”,this.value);
})
secondColor.addEventListener('input',function(){
document.documentElement.style.setProperty(“--second color”,this.value)
})
:根目录{
--主色:黑色;
--第二种颜色:白烟;
--主字号:16px;
颜色:var(--主色);
字体大小:var(--主字体大小);
}

问题在于,您正在设置“样式”属性,以便每次重写之前的所有内联样式

您需要使用
setProperty

var mainColor=document.getElementById(“主颜色”);
var secondColor=document.getElementById(“第二种颜色”);
函数颜色(CSS变量,输入值){
返回CSSVVariable+“:”+inputValue
}
mainColor.addEventListener('input',function()){
document.documentElement.style.setProperty(“--main color”,this.value);
})
secondColor.addEventListener('input',function(){
document.documentElement.style.setProperty(“--second color”,this.value)
})
:根目录{
--主色:黑色;
--第二种颜色:白烟;
--主字号:16px;
颜色:var(--主色);
字体大小:var(--主字体大小);
}

更改此行
document.documentElement.setAttribute(“style”,color(--main color,this.value))

document.documentElement.style.setProperty(“--main color”,this.value)

参考:

演示:

更改此行
document.documentElement.setAttribute(“style”,color(--main color,this.value))

document.documentElement.style.setProperty(“--main color”,this.value)

参考:


演示:

您的代码似乎正常工作fine@TemaniAfifgif addedwe不需要gif,我们需要一个可运行的代码来突出显示issue@TemaniAfif检查图片也,我认为有非常有用的信息。如果没有线索,我将添加可运行代码。您的代码似乎工作正常fine@TemaniAfifgif addedwe不需要gif,我们需要一个可运行的代码来突出显示issue@TemaniAfif检查图片也,我认为有非常有用的信息。如果没有线索,我会加上我不知道的可运行代码。非常感谢。我不知道。非常感谢。