2017-11-10 4 views
0

多かれ少なかれ、各要素は異なるクラス名を持っています。複数のHTML要素の背景色をJavascriptで切り替える方法は? (固定)

HTML要素:

<section class = "top-nav"> 
<h3 class = "top-left-heading">Hot</h3> 
<h3 class = "top-right-heading">Items</h3> 
<h3 class = "bottom-left-heading">Interaction</h3> 
<h3 class = "bottom-right-heading">Location</h3> 
<section class = "footer"> 

のJavascript機能:

var theme 
function toggleTheme(){ 
    var bars = document.querySelectorAll('.heading' + '.nav' + '.header' + 
'footer') 
    if (theme == "blue"){ 
     for (var i = 0; i < bars.length; i++){ 
      bars[i].style.backgroundColor = "#11C034"; 
     } 
     theme = "green" 
    } 
    else{ 
     for (var i = 0; i < bars.length; i++){ 
      bars[i].style.backgroundColor = "#428bca"; 
     } 
     theme = "blue" 
    } 

} 
+0

あなたは、オブジェクトに複数のクラス名に影響を与えることができます。 – JMichelB

+1

'.heading' + '.nav' + '.header' + 'footer'を'heading、.nav、.header、.footer 'に変更してください – jeff

+0

'var bars = document.querySelectorAll(')が必要です。 h3、.header、.footer '); ' –

答えて

0

おそらくより良い方法は、単にbody要素にクラス.theme-blackを追加することです。

.top-nav { 
    // basic CSS colors... 
} 
.theme-black .top-nav { 
    background: #000; 
} 

このように、JavaScriptを最小限に抑えてCSSにスタイルをさせることができます。

1

あなたのセレクタの構文が正しくありません。

var bars = document.querySelectorAll('.heading' + '.nav' + '.header' + 'footer') 
  • まず、これはあなたが望んでいた場合を除き方法ではなく、文字列の 連結(に渡される別のセレクターを分離するカンマで一つの大きな文字列でなければなりませんあなたがしていない可変データを組み込むこと)。
  • 2番目に、参照するクラスは実際にはあなたのHTMLで使用している のクラスではありません。

正しい構文は次のようになります。

document.querySelectorAll(".top-left-heading, .top-right-heading, .bottom-left-heading, .bottom-right-heading") 

次に、if/thenまたはインラインスタイルのためのすべての必要はありません。必要なテーマのクラスを設定し、問題のHTML要素にデフォルトのクラス(テーマ)を設定してから、これらのクラスの使用をいくつかのトリガーで切り替えるだけです。

document.querySelector("button").addEventListener("click", toggleTheme); 
 

 
function toggleTheme(){ 
 
    // Get all the headings into a node list and then convert that node list to an array 
 
    var bars = Array.from(document.querySelectorAll(".top-left-heading, .top-right-heading, .bottom-left-heading, .bottom-right-heading")); 
 

 
    // Loop through the array 
 
    bars.forEach(function(bar){ 
 
    // Toggle the use of the classes 
 
    bar.classList.toggle("green"); 
 
    bar.classList.toggle("blue"); 
 
    }); 
 
}
.green { 
 
    background-color :green; 
 
    color:yellow; 
 
} 
 

 
.blue { 
 
    background-color :blue; 
 
    color:pink; 
 
}
<section class = "top-nav"> 
 
    <h3 class = "top-left-heading green">Hot</h3> 
 
    <h3 class = "top-right-heading green">Items</h3> 
 
    <h3 class = "bottom-left-heading green">Interaction</h3> 
 
    <h3 class = "bottom-right-heading green">Location</h3> 
 
<section class = "footer"> 
 

 
<button type="button">Toggle Theme</button>

関連する問題