Return background color of clicked element js

为君一笑 提交于 2020-01-06 15:43:10

问题


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


来源:https://stackoverflow.com/questions/10720620/return-background-color-of-clicked-element-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!