2017-01-29 12 views
0
document.getElementById("button2").addEventListener("click", function({ 
    document.getElementById("box").body.style.backgroundColor = "Blue"; 
}); 

私がクリックするとボックスの色が変わることはありません。コードのどこに誤りがありますか?Javascriptでボタンの色を変えることができない

+1

そして、あなたの( "* [MCVE] *")HTMLにbodyタグを持っていますか?コンソールにエラーがありますか? –

+0

'document.getElementById(" box ")。body.style.backgroundColor'を' document.getElementById( "box")に置き換えます。style.backgroundColor' –

+0

これは非常に新しいものです。 // Growボタン document.getElementById( "button1")。addEventListener( "click"、function(){document.getElementById( "box")。style.height = "250px";}); // blueボタン document.getElementById( "button2")。addEventListener( "click"、function(){document.getElementById( "box")。body.style.backgroundColor = "Blue";}); –

答えて

1

すでにIDのボックスのある要素を選択しているので、.bodyを削除する必要があります。

document.getElementById("button2").addEventListener(
    "click", 
    function(){ 
     document.getElementById("box").style.backgroundColor = "Blue"; 
    } 
); 
0

querySelectorを使用して要素を選択します。このようなボタンのクリックイベントを処理します。あなたはそれをやっている

var btn = document.querySelector("#button2");//select your button 
 
btn.addEventListener('click',function(){//handle click event 
 
document.querySelector("#box").style.backgroundColor="Blue";//select box id and set background 
 
});
<button id="button2"/>Click</button> 
 
<p id="box"> 
 
change color 
 
</p>

0

は、次の2つの方法wrong.Thereであること

まず::

document.getElementById("button2").addEventListener(
 
     "click", 
 
     function(){ 
 
      document.getElementById("box").style.backgroundColor = "Blue"; 
 
     } 
 
    );

セカンド::もしy OUあなたのDOM

document.body.getElementById("button2").addEventListener(
 
     "click", 
 
     function(){ 
 
      document.getElementById("box").style.backgroundColor = "Blue"; 
 
     } 
 
    );

関連する問題