最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Return background color of clicked element js - Stack Overflow

programmeradmin0浏览0评论

I want to send the background color of an element to a function using javascript for example:

<td style="background-color:#ff0000" onClick="getColor()"></td>

Could anyone please give me a pointer as to what I have to do in the getColor() function?

I want to send the background color of an element to a function using javascript for example:

<td style="background-color:#ff0000" onClick="getColor()"></td>

Could anyone please give me a pointer as to what I have to do in the getColor() function?

Share Improve this question asked May 23, 2012 at 13:09 StuyvensteinStuyvenstein 2,4472 gold badges28 silver badges36 bronze badges 2
  • 1 possible duplicate of How to get the background color of an element using javascript? – Barry Kaye Commented May 23, 2012 at 13:12
  • @BarryKaye This is not a duplicate coz that article applies to a single element, I want to use the same function in the onclick method for multiple elements getting their background colors – Stuyvenstein Commented May 23, 2012 at 13:16
Add a ment  | 

3 Answers 3

Reset to default 2

change this to:

<td style="background-color:#ff0000" onClick="getColor(this)"></td>

And this would be the javasctipt:

getColor(elem){
    alert(elem.style.backgroundColor);
}

If jQuery is ok:

<td style="background-color:#ff0000" onClick="getColor(this)"></td>
<script>
function getColor(element) {
    var bgColor = $(element).css('background-color');
    // ... do something with bgColor here...
}
</script>

Modify the call to send the object as param. Like this-

<td style="background-color:#ff0000" onClick="getColor(this)"></td>

And the function would be-

function getColor(obj){
 var bgColor = obj.style.backgroundColor;
 alert(var);
}
发布评论

评论列表(0)

  1. 暂无评论