2017-01-28 16 views
1
document.getElementById("sgun").style.backgroundColor = "#00FA9A"; 

我想定义document.getElementById和style.backgroundColor =“#00FA9A”;作为一个变量,所以代码看起来不可怕,而且我不必为每个元素都复制粘贴。我该怎么做?将dom对象定义为变量的Javascript

回答

1

你可能只是使采取ID和风格,为你做它的功能,如:

function css(id, prop, value){ 
    document.getElementById(id).style[prop] = value; 
} 

,然后用它喜欢:

css('sgun', 'backgroundColor', '#00FA9A'); 
// css(...); 

如果你想要一个只改变背景颜色的函数为'#0 0FA9A”使用本:

function bg(id){ 
    document.getElementById(id).style.background = '#00FA9A'; 
} 

,并用它喜欢:

bg('sgun'); 
bg('someotherid'); 
// ... 
0

我会建议让它成为一个函数。

function changeBgColor(el) { 
 
document.getElementById(el).style.backgroundColor = '#00fa9a'; 
 
} 
 
changeBgColor('foo'); 
 
changeBgColor('bar');
<div id="foo">asdf</div> 
 
<div id="bar">asdf</div>