2017-01-06 63 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";