Return background color of clicked element js

2019-09-15 19:43发布

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?

3条回答
Ridiculous、
2楼-- · 2019-09-15 19:57

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);
}
查看更多
仙女界的扛把子
3楼-- · 2019-09-15 20:09

change this to:

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

And this would be the javasctipt:

getColor(elem){
    alert(elem.style.backgroundColor);
}
查看更多
霸刀☆藐视天下
4楼-- · 2019-09-15 20:09

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>
查看更多
登录 后发表回答