有没有办法反转父div中的每个颜色集,或者我只需要为它构建一个新的样式表?
谢谢!
答案 0 :(得分:4)
在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>
答案 1 :(得分:2)
通过“every color set within a parent div
”,我假设也想要子节点。此外,前景色和背景色都要切换(边框颜色很简单)。
See the live demo at 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 + ')';
}
答案 2 :(得分:2)
有点迟了但迟到了,从来没有:
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, 0, 0.3)"), // 0, 255, 255, 0.7
invert("rgb(255, 0, 0)"), // 0, 255, 255
invert("255, 0, 0"), // 0, 255, 255
invert(255, 0, 0) // 0, 255, 255
);