问题描述
|
有什么办法可以反转父div内的每种颜色设置,还是只需要为其构建一个新的样式表?
谢谢!
解决方法
通过\“
every color set within a parent div
\”,我假设也需要子节点。同样,前景色和背景色都将被切换(带有边框颜色的简单mod)。
请参阅jsFiddle上的实时演示。
反转所有颜色,例如:
var Container = $(\"#Container\");
invertElementColors (Container);
//--- Now invert all children.
Container.find (\'*\'). each (function () {
invertElementColors ( $(this) );
} );
鉴于:
function invertElementColors (jNode) {
jNode.css ( {
\'color\' : function (J,oldColor) {
return invertRGB_ColorStr (oldColor);
},\'background-color\' : function (J,oldColor) {
return invertRGB_ColorStr (oldColor);
}
//--- Add other color properties,like border,as desired.
} );
}
function invertRGB_ColorStr (oldColorStr) {
//--- Special case
if (oldColorStr == \'transparent\') oldColorStr = \'rgb(255,255,255)\';
//--- Color is text in RGB format. EG: rgb(1,22,255)
var colorArray = oldColorStr.match (/\\((\\d+),\\s?(\\d+),\\s?(\\d+)\\)/);
var newColorStr = $.map (colorArray,function (byte,J) {
if (!J) return null;
//--- Invert a decimal byte.
return Math.abs (255 - parseInt (byte) );
}
).join (\',\');
return \'rgb(\' + newColorStr + \')\';
}
,在http://jsfiddle.net/cZNRZ/上进行处理。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">
<title> - jsFiddle demo</title>
<script type=\'text/javascript\' src=\'http://code.jquery.com/jquery-1.6.js\'></script>
<style type=\'text/css\'>
span {color:blue;}
#hello {color:red;}
</style>
<script type=\'text/javascript\'>
//<![CDATA[
function invertColor (rgbString) {
var parts = rgbString.match(/^rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)$/);
parts.splice(0,1);
parts = $.map(parts,function (item) {
return (255-parseInt(item,10));
}
);
return \'rgb(\' + parts.join(\',\') + \')\';
}
function invertme () {
$(\'#hello\').parent().find(\'*\').each(function () {
var color = $(this).css(\'color\');
$(this).css(\'color\',invertColor(color));
});
}
$(function () {
$(\'#button\').click(invertme);
});
//]]>
</script>
</head>
<body>
<div>
<span id=\"hello\">Hello</span>
<span>World</span>
</div>
<input type=\"button\" value=\"invert\" id=\"button\"/>
</body>
</html>
,迟了一点,但迟到总比没有好:
function invert(rgb) {
rgb = Array.prototype.slice.call(arguments).join(\",\").match(/(-?[0-9\\.]+)/g);
for (var i = 0; i < rgb.length; i++) {
rgb[i] = (i === 3 ? 1 : 255) - rgb[i];
}
return rgb.join(\",\");
}
console.log(
invert(\"rgba(255,0.3)\"),// 0,0.7
invert(\"rgb(255,0)\"),255
invert(\"255,0\"),255
invert(255,0) // 0,255
);