将dom对象定义为变量的Javascript
我想定义document.getElementById和style.backgroundColor=“#00FA9A”;作为一个变量,代码看起来并不可怕,我不必为每个元素复制粘贴它。我该怎么做 我建议把它变成一个函数将dom对象定义为变量的Javascript,javascript,css,variables,dom,getelementbyid,Javascript,Css,Variables,Dom,Getelementbyid,我想定义document.getElementById和style.backgroundColor=“#00FA9A”;作为一个变量,代码看起来并不可怕,我不必为每个元素复制粘贴它。我该怎么做 我建议把它变成一个函数 功能更改颜色(el){ document.getElementById(el.style.backgroundColor='#00fa9a'; } changeBgColor('foo'); 更改颜色(“条”) asdf asdf您只需制作一个带有ID和样式的函数,然后根据自
功能更改颜色(el){
document.getElementById(el.style.backgroundColor='#00fa9a';
}
changeBgColor('foo');
更改颜色(“条”)代码>
asdf
asdf
您只需制作一个带有ID和样式的函数,然后根据自己的喜好进行操作:
document.getElementById("sgun").style.backgroundColor = "#00FA9A";
然后像这样使用它:
function css(id, prop, value){
document.getElementById(id).style[prop] = value;
}
function bg(id){
document.getElementById(id).style.background = '#00FA9A';
}
如果您想要一个只将背景颜色更改为“#00FA9A”的函数,请使用以下命令:
css('sgun', 'backgroundColor', '#00FA9A');
// css(...);
然后像这样使用它:
function css(id, prop, value){
document.getElementById(id).style[prop] = value;
}
function bg(id){
document.getElementById(id).style.background = '#00FA9A';
}