因此,如果我有一个文本“Click Me to Brighten”,它具有一些深绿色十六进制颜色的CSS颜色属性,如“#00801a”,我想这样做,以便当我点击它时,它会使它变成浅绿色.同样,如果它是一些蓝色,点击它会使它变成浅蓝色.基本上我想知道是否有办法在不知道实际颜色的情况下改变css颜色.
解决方法
转换为HSV以改变brigthness
See the full code example on jsFiddle
此版本使用HSV.我将原始rgb值转换为hsv并更改v的值以获得更浅的颜色.我从Pointy回答了RgbToHsv
,我刚刚为灰色添加了一点修复.我得到了HsvToRgb
on this website
当页面加载时,我将rgb转换为hsv更改v值,转换回rgb并使用新值更改元素的css.
function AppendColor(light) { $(".dark").each(function(i){ // get the RGB from existing elements var color = $(this).css("background-color"); color = color.replace(/[^0-9,]+/g,""); var red = color.split(",")[0]; var gre = color.split(",")[1]; var blu = color.split(",")[2]; // convert rgb to hsv var hsv = RgbToHsv(red,gre,blu); // convert hsv to rgb modifing the `v` param var rgb = HsvToRgb(hsv.h,hsv.s,light); // creates a new div and set the new background // then appends to the content color = "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")"; $("<div />") .css("background",color) .attr("title",color) .appendTo($(".light").parent()); $("<span />").html(" ").appendTo($(".light").parent()) }); $("<br />").appendTo($(".light").parent()) } // tested values AppendColor(25); AppendColor(50); AppendColor(75); AppendColor(90); AppendColor(95); AppendColor(97); AppendColor(99); AppendColor(100);
结果:
通过最高颜色增加颜色值
顶部的div表示深色(rgb)#801A00,#00801A,#1A0080和#D2D2D2
<div id="red" class="dark red"></div> <div id="green" class="dark green"></div> <div id="blue" class="dark blue"></div> <div id="gray" class="dark gray"></div> <br /> <div id="lred" class="lred"></div> <div id="lgreen" class="lgreen"></div> <div id="lblue" class="lblue"></div> <div id="lgray" class="lgray"></div>
底部的div将从黑暗中获得浅色.
当我点击一个黑暗的div时,它将检索背景颜色,拆分值并发送到Lighthen功能.此功能将使颜色更亮.
function Lighthen(red,green,blue) { var max = ([red,blue].sort(function(l,r){return r-l}))[0]; var multiplier = max; multiplier = (multiplier / 255) + 1; // if it would still be too dark,make it lighten more if (multiplier < 1.5) multiplier = 1.9; // if it gets to white,move away a bit if ((max * multiplier) > 255) { multiplier = (multiplier / 230) + 1; } var r = Math.round(red * multiplier); var g = Math.round(green * multiplier); var b = Math.round(blue * multiplier); if (r > 255) r = 255; if (g > 255) g = 255; if (b > 255) b = 255; return "rgb(" + r + "," + g + "," + b + ")"; }
单击暗div时,将计算新颜色并在对应的div上更改.
$(".dark").click(function(){ var color = $(this).css("background-color"); color = color.replace(/[^0-9,""); var red = color.split(",")[0]; var gre = color.split(",")[1]; var blu = color.split(",")[2]; $("#l" + $(this).attr("id")) .css("background",Lighthen(red,blu)); });
导致