Return background color of clicked element js

2019-09-15 19:22发布

问题:

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?

回答1:

change this to:

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

And this would be the javasctipt:

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


回答2:

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>


回答3:

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);
}