基本的に、ボタンをクリックするだけで JavaScript を使用して CSS の要素の背景色を変更したいと考えています。
これまでのところ、私の CSS は次のようになっています。
div.box {
width:100px;
height:100px;
background-color:#FF2400;
}
複数のボタンを使用するだけで、複数の色の選択に動的に変更する必要があります (それぞれが異なる色です)。
基本的に、ボタンをクリックするだけで JavaScript を使用して CSS の要素の背景色を変更したいと考えています。
これまでのところ、私の CSS は次のようになっています。
div.box {
width:100px;
height:100px;
background-color:#FF2400;
}
複数のボタンを使用するだけで、複数の色の選択に動的に変更する必要があります (それぞれが異なる色です)。
完了: http://jsfiddle.net/iambriansreed/zmtU4/
非 jQuery に更新されました。
HTML
<div id="box"></div><div id="box"></div>
<button type="button" onclick="button_click('red');">Red</button>
<button type="button" onclick="button_click('blue');">Blue</button>
<button type="button" onclick="button_click('green');">Green</button>
<button type="button" onclick="button_click('yellow');">Yellow</button>
<button type="button" onclick="button_click('purple');">Purple</button>
純粋な JavaScript
function button_click(color){
document.getElementById("box").style.backgroundColor=color;
}
これを行うバニラ JavaScript の方法は、要素への参照を取得し、それを使用style.backgroundColor
して色を変更することです。
たとえば、div にあなたの ID があるmyBox
場合は、
document.getElementById("myBox").style.backgroundColor="#000000"; // change to black
実際の例: http://jsfiddle.net/QWgcp/
ちなみに、この種の操作を頻繁に行う場合は、jQuery などのフレームワークがコードの作成に役立ちます。jQuery を使用した同じ機能は、もう少し単純になります。
$('#myBox').css('background-color','#000000');
単一の要素を変更するのではなく、代わりに CSS ルールを変更したいので、一致するすべての要素が影響を受けることを正しく理解していますか? 例のスタイルを動的に青色に変更する方法の例を次に示します。
<html>
<head>
<style>
div.box{
width:100px;
height:100px;
background-color:#FF2400;
}
</style>
<script>
var sheet = document.styleSheets[0] // Of course if you have more than one sheet you'll have to find it among others somehow
var rulesList = sheet.cssRules || sheet.rules // some older browsers have it that way
var rule = rulesList[0] // same for rules - more than one and you'll have to iterate to find what you need
rule.style.backgroundColor = 'blue' // and voila - both boxes are now blue
</script>
</head>
<body>
<div class="box"></div>
<div class="box"></div>
</body>
</html>
このピースを「クリック」イベントハンドラーとしてボタンに割り当てるだけで、設定は完了です。