document.getElementById("button2").addEventListener("click", function({
document.getElementById("box").body.style.backgroundColor = "Blue";
});
私がクリックするとボックスの色が変わることはありません。コードのどこに誤りがありますか?Javascriptでボタンの色を変えることができない
document.getElementById("button2").addEventListener("click", function({
document.getElementById("box").body.style.backgroundColor = "Blue";
});
私がクリックするとボックスの色が変わることはありません。コードのどこに誤りがありますか?Javascriptでボタンの色を変えることができない
すでにIDのボックスのある要素を選択しているので、.body
を削除する必要があります。
document.getElementById("button2").addEventListener(
"click",
function(){
document.getElementById("box").style.backgroundColor = "Blue";
}
);
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>
は、次の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";
}
);
そして、あなたの( "* [MCVE] *")HTMLにbodyタグを持っていますか?コンソールにエラーがありますか? –
'document.getElementById(" box ")。body.style.backgroundColor'を' document.getElementById( "box")に置き換えます。style.backgroundColor' –
これは非常に新しいものです。 // 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";}); –