2016-09-19 22 views
0

我一直坐在這個問題上2小時。我試圖做的是一個網站,你按下一個按鈕,它會改變顏色。我知道這可以用CSS完成,但我對此不感興趣。當我使用Javascript時,ID正在接管我的課程

主要問題是,當我按下按鈕時,什麼也沒有發生..但是,如果我從'CSS#'中刪除'#sug'一切正常......所以我想要做的是使佈局非常基本的開始,所以沒有什麼,除了像黑色背景,當我按下按鈕時,它應該切換..

另外,我知道你可以在按鈕標籤中實現onclick,但這不是什麼我要去。我想知道爲什麼會發生這種情況,以及我如何解決這個問題。

這裏是我的JavaScript,CSS和HTML代碼:

window.onload = setUp; 
 

 
function setUp() { 
 
    document.getElementById("normal").onclick = setNormalStyle; 
 
    document.getElementById("crazy").onclick = setCoolStyle; 
 
    document.getElementById("insane").onclick = setInsaneStyle; 
 
} 
 

 
function setNormalStyle() { 
 
    var messageBox = document.getElementById("sug"); 
 
    messageBox.className = "normal"; 
 
} 
 

 
function setCoolStyle() { 
 
    var savingTheSecondVar = document.getElementById("sug"); 
 
    savingTheSecondVar.className = "cool"; 
 
} 
 

 
function setInsaneStyle() { 
 
    var savingTheThirdVar = document.getElementById("sug"); 
 
    savingTheThirdVar.className = "insane"; 
 
}
#sug { 
 
    background-color: black; 
 
} 
 
.normal { 
 
    height: 500px; 
 
    background-color: blue; 
 
    color: white; 
 
    padding: 30px; 
 
    margin: auto; 
 
    width: 500px; 
 
} 
 
.insane { 
 
    height: 500px; 
 
    background-color: green; 
 
    padding: 30px; 
 
    margin: auto; 
 
    width: 500px; 
 
    color: white; 
 
} 
 
.cool { 
 
    height: 500px; 
 
    background-color: red; 
 
    padding: 30px; 
 
    margin: auto; 
 
    width: 500px; 
 
    color: white; 
 
}
<!DOCTYPE html> 
 

 
<html> 
 

 
<head> 
 
    <meta charset="utf-8" /> 
 
    <link type="text/css" rel="stylesheet" href="Struktur.css" /> 
 
    <script type="text/javascript" src="struktur.js"></script> 
 
    <title>My first Javascript project</title> 
 
</head> 
 

 
<body> 
 
    <div id="sug" class="cool insane normal"> 
 
    <header> 
 
     <h1> Welcome to this Javascript site! </h1> 
 
    </header> 
 
    <section> 
 
     <p> 
 
     text 
 
     </p> 
 
    </section> 
 
    <button type="button" id="normal">First style</button> 
 
    <button type="button" id="crazy">Second style</button> 
 
    <button type="button" id="insane">Third style</button> 
 
    </div> 
 
</body> 
 

 
</html>

+2

ID規則將否決類規則。這就是CSS的工作原理。 –

+0

https://www.smashingmagazine.com/2007/07/css-specificity-things-you-should-know/ - 關於主題的一篇很好的文章 –

+2

現在事實上的標準是根本不使用ID的CSS - 僅適用於JavaScript。 – ippi

回答

3

的問題是你的CSS。

#sug{ 
    background-color: black; 
} 

覆蓋類的背景顏色,因爲它是更具體的選擇器(即id選擇器)。

改變你的類在CSS其餘包括像

#sug.normal,#sug.insane,#sug.cool等ID

這裏是CSS特異性的好文章以幫助您瞭解更多信息:https://css-tricks.com/specifics-on-css-specificity/

0

這是因爲,一個ID擁有超過一類偏好。你需要這樣指定它:

#sug.cool { background: red; } 

0

您不會刪除按鈕的CSS onClick()事件中#sug id提供的背景顏色。 Id對類有更多偏好

使用下面的代碼是個好習慣,因爲類之間有空格,如果要添加多個類,可以使用它。

messageBox.className += " " + "normal"; 
相關問題