獲取html元素當前的背景顏色

/**
	 * 獲取元素的當前背景顏色
	 */
	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;
	}
相關文章
相關標籤/搜索