如何在点击时将html颜色输入值设置为div颜色

如果单击div,则html5颜色输入值应设置为单击的div颜色和背景颜色值。

我试过代码

$(function() { $("#changeMe").on('click', function() { $('#designer-javascript-color').val($(this).css("color")); $('#designer-javascript-backcolor').val($(this).css("background-color")); }); }); 
 Selected item color:  
Selected item background color:
click here

单击后单击我,两个输入仍然是黑色。 如何解决这个问题,使白​​色和蓝色的颜色在输入?

测试用例位于http://jsfiddle.net/bpc2w43w/

在使用之前将rgb值转换为hex:

 function rgbToHex(rgb) { var a = rgb.split("(")[1].split(")")[0].split(","); return "#" + a.map(function(x) { x = parseInt(x).toString(16); return (x.length == 1) ? "0"+x : x; }).join(""); } $(function () { $("#changeMe").on('click', function() { $('#designer-javascript-color').val(rgbToHex($(this).css("color"))); $('#designer-javascript-backcolor').val(rgbToHex($(this).css("background-color"))); }); }); 
  Selected item color:  
Selected item background color:
click here

$(this).css('color')$(this).css('background-color')的值是RGB值。 因此,您需要将其转换为hex值。 借用某人的解决方案来转换价值,这是解决问题的方法。

 $(function() { $('#changeMe').on('click', function() { $('#designer-javascript-color').val(rgb2hex($(this).css('color'))); $('#designer-javascript-backcolor').val(rgb2hex($(this).css('background-color'))); }); }); var hexDigits = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]; //Function to convert hex format to a rgb color function rgb2hex(rgb) { rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); } function hex(x) { return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16]; } 

这很有效

  Selected item color:  
Selected item background color:

此外,当您在选择器中选择颜色时,请记住移动颜色选择器右侧的滑块,以便可以选择较浅的颜色。

 $("#changeMe").click(function() { var a = $("#designer-javascript-color").val(); var b= $("#designer-javascript-backcolor").val(); $("#changeMe").css({ 'color' : a, 'background-color': b }); });