使用javascript,当我点击它时,如何获得表格单元格的背景颜色? [英] Using javascript, how do I get the background color of a table cell when I click on it?

查看:94
本文介绍了使用javascript,当我点击它时,如何获得表格单元格的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要弹出一个警报,只要点击它就可以显示表格单元格的背景。我似乎无法找到或弄清楚如何获取背景颜色。



我的表格单元格如下所示:

 < td id =s0onclick =selectCell(event)> 0< / td> 

我的selectCell函数如下所示:

 函数selectCell(e){
alert(e.target.backgroundColor); //这给了我'未定义'
alert(e.target.bgcolor); //这给了我'未定义'
alert(e.target.bgColor); //没有任何显示。我不相信这是一个有效的财产
//一旦我知道我正确地抓住了颜色,我会在这里做它的东西。
}

我的CSS看起来像这样:

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

任何帮助将不胜感激!

解决方案

节点的样式位于styles属性中,例如:

  e.target.style.backgroundColor; 

然而,这只适用于使用内联样式属性。如果使用样式表分配CSS(应该是),则需要使用:

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

不幸的是,Internet Explorer并未实现 getComputedStyle() code>选项,而不是提供 currentStyle (注意,它们不支持 e.target 认为,至少在8之前的版本?)。我没有用于测试的Internet Explorer,但文档建议它应该被使用:

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

参考文献:


I want to have an alert pop up that shows me the background of a table cell whenever i click on it. I just can't seem to find or figure out how to grab the background color.

My table cell looks like this:

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

My selectCell function looks like this:

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.
}

My CSS looks like this:

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

Any help would be greatly appreciated!!

解决方案

The styles of a node are in the styles property, for example:

e.target.style.backgroundColor;

However this works only for those styles declared with the in-line style attribute. If CSS is assigned (as it should be) using a stylesheet, you'll need to use:

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

Internet Explorer, unfortunately, doesn't implement the getComputedStyle() option, instead offering currentStyle (mind, they don't support e.target either, I think, at least in versions prior to 8?). I don't have Internet Explorer with which to test, but the docs suggest that it should be used:

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

References:

这篇关于使用javascript,当我点击它时,如何获得表格单元格的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆