Home  >  Article  >  Web Front-end  >  js code to get the real background color of an element_javascript skills

js code to get the real background color of an element_javascript skills

WBOY
WBOYOriginal
2016-05-16 19:06:511464browse


[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute
]<script> function getBg(element) {//author: Longbill (www.longbill.cn) //dnew.cn修补 var rgbToHex=function(rgbarray,array){ if (rgbarray.length < 3) return false; if (rgbarray.length == 4 && rgbarray[3] == 0 && !array) return 'transparent'; var hex = []; for (var i = 0; i < 3; i++){ var bit = (rgbarray[i] - 0).toString(16); hex.push((bit.length == 1) ? '0' + bit : bit); } return array ? hex : '#' + hex.join(''); } //--------------- if (typeof element == "string") element = document.getElementById(element); if (!element) return; cssProperty = "backgroundColor"; mozillaEquivalentCSS = "background-color"; if (element.currentStyle) var actualColor = element.currentStyle[cssProperty]; else { var cs = document.defaultView.getComputedStyle(element, null); var actualColor = cs.getPropertyValue(mozillaEquivalentCSS).match(/\d{1,3}/g); //----- actualColor = (actualColor) ? rgbToHex(actualColor) : "transparent"; } if (actualColor == "transparent" && element.parentNode) return arguments.callee(element.parentNode); if (actualColor == null) return "#ffffff"; else return actualColor; } function go() { for(var i=1;i<=4;i++) eval("alert('div"+i+":'+getBg('div"+i+"'));"); } </script>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn