2017-01-06 62 views
0

我有以下的功能,一旦它被执行reset SA button和适用的造型:改变大块的风格与JavaScript的

function reset(){ 
    var boxes = getBoxes(); 
    for(i = 0 ; i < boxes.length; i++) { 
     boxes[i].innerHTML = ""; 
    } 
document.getElementById("start_button").innerHTML = "Start Game"; 
document.getElementById("start_button").setAttribute('onclick', 'gameStart()'); 
document.getElementById("start_button").style.color = "black"; 
document.getElementById("start_button").style.backgroundColor = "lightgreen"; 

}

然而,正如你所看到的,是越来越重复更改函数中的每个样式元素。特别是,如果我需要应用该样式:

#button{ 
    text-align: center; 
} 
#start_button{ 
    width: 10%; 
    height: 50px; 
    margin-top: 4%; 
    margin-left: auto; 
    margin-right: auto; 
    background: lightgreen; 
    color:black; 
} 

#start_button:hover { 
    background: green; 
    color: white; 
} 

有没有在JavaScript的方式链接到的样式代码一整块?

+0

http://stackoverflow.com/questions/3968593/how-to-设置多CSS样式 - 属性 - 在JavaScript的 –

+2

为什么不只是添加类元素。并设置CSS的那类 –

+0

所以到目前为止,你可以通过一个字符串或将其设置为一个类设置。 web dev中的最佳实践是什么? 。 – alexp2603

回答

0

如果将start_button更改为类;这应该是因为页面上会有不止一个;你可以使用className属性。

CSS:

.start_button{ 
    width: 10%; 
    height: 50px; 
    margin-top: 4%; 
    margin-left: auto; 
    margin-right: auto; 
    background: lightgreen; 
    color:black; 
} 

.start_button:hover{ 
    background:green; 
    color: white; 
} 

看起来就像你正在创建按钮,这样你可以抓住的按钮 JS:

document.getElementsByTagName("button").className = "start_button";