2013-06-14 15 views
5

私はそれをクリックするたびにテーブルセルの背景を表示するアラートポップアップを持っています。私はちょうど背景色をつかむ方法を見つけたり見つけたりできないようです。JavaScriptを使用して、表のセルをクリックしたときにその背景色を取得するにはどうすればよいですか?

私のテーブルのセルは次のようになります。

<td id="s0" onclick="selectCell(event)">0</td> 

マイselectCell機能は次のようになります。

function selectCell(e){ 
    alert(e.target.backgroundColor); //this gives me 'undefined' 
    alert(e.target.bgcolor);   //this gives me 'undefined' 
    alert(e.target.bgColor);   //nothing shows up. i don't believe this is a valid property 
    //once i know i am properly grabbing the color i will do stuff with it here. 
} 

私のCSSは次のようになります。

#s0 { 
    border: 1px solid; 
    background-color: yellow; 
} 

すべてのヘルプは大だろう感謝!!

答えて

4

ノードのスタイルは、たとえば、スタイルプロパティに、次のとおりです。

e.target.style.backgroundColor; 

しかしこれは、インラインstyle属性で宣言されたもののスタイルのためにのみ機能します。 CSSはスタイルシートを使用して(それがあるべきとして)割り当てられている場合は、使用する必要があります:

window.getComputedStyle(e.target, null).backgroundColor; 

のInternet Explorer、残念ながら、代わりにcurrentStyle(心を提供し、getComputedStyle()オプションを実装していない、彼らは「ドンtサポートe.targetのいずれか、私は、少なくとも8以前のバージョンでは?)。私はテストすると、Internet Explorerを持っていないが、ドキュメントは、それが使用されるべきであることを示唆して

var e = window.event ? window.event : e, 
    elementNode = e.target !== null ? e.target : e.srcElement; 
elementNode.currentStyle.backgroundColor; 

参考文献:

+1

ことであるスタイルではないスタイル – bugwheels94

+0

@Ankit:ありがとう...くそ、興奮性のタッチタイピング... X( –

+0

あなたの第2のものは素晴らしいです – bugwheels94

-1
あなたは詳細について簡単にjQueryのCSS()関数

jQuery(document).ready(function(){ 
    $(this).click(function() { 
      var color = $(this).css("background-color"); 
      alert(color); 
    }); 
}); 

でそれを行うことができます

が持っているthis例を見

関連する問題