Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将dom对象定义为变量的Javascript_Javascript_Css_Variables_Dom_Getelementbyid - Fatal编程技术网

将dom对象定义为变量的Javascript

将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和样式的函数,然后根据自

我想定义document.getElementById和style.backgroundColor=“#00FA9A”;作为一个变量,代码看起来并不可怕,我不必为每个元素复制粘贴它。我该怎么做

我建议把它变成一个函数

功能更改颜色(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';
}