2012-04-24 11 views
2

基本的には、ボタンをクリックしてJavaScriptを使用してCSSの要素の背景色を変更したいと思います。それは、(それぞれが異なる色である)複数のボタンがどうなるだけで、いくつかの色の選択に動的に変更する必要があるJavascriptを使用してCSSの要素の背景色を変更する

div.box { 
    width:100px; 
    height:100px; 
    background-color:#FF2400; 
} 

これまでのところ、私のCSSは次のようになります。

+0

jquery:http://api.jquery.com/css/を使用するか、DOMを使用して次のようなスタイルを変更します。document.body.yourelementname.style.backgroundColor = "#FECE03" – renard

+0

ここで役立つものは何ですか? – iambriansreed

答えて

0

これを行うにはバニラ、JavaScriptの方法は、要素への参照を取得し、色を変更するstyle.backgroundColorを使用することです:DIVはmyBoxのIDを持っている場合

たとえば、あなたが使用する

document.getElementById("myBox").style.backgroundColor="#000000"; // change to black 

ライブ例:あなたは、このようなjQueryのような操作フレームワークのこの種の多くをやっている場合http://jsfiddle.net/QWgcp/

ところで、コードを書くことでいくつかの助けを提供します。 jQueryのを使用して、同じ機能が少し簡素次のようになります。

$('#myBox').css('background-color','#000000'); 
+0

あなたのフィドルでそれを持っているので私のDVを削除しました。 OPはボタンを求めた。 – iambriansreed

6

は完了:非jQueryのようにhttp://jsfiddle.net/iambriansreed/zmtU4/

を更新しました。

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; 
}​ 
+0

-1の理由は何ですか? – iambriansreed

+0

-1はjsfiddleのみの回答です。 jQueryのみの解決策では-1の質問には 'jQuery'タグは付いていません。 + 1 jafiddle @Jamiec Pure JSの解決策です。 – Jamiec

+0

コードが含まれています。あなたの+1を待っています。 – iambriansreed

0

私が正しくあなたの代わりに、その一致するすべての要素が影響を受けることになる単一の要素が、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> 

ジャストボタンを「クリック」イベントハンドラとしてこの作品を割り当て、あなたが設定されています。

関連する問題