如何在点击时将html颜色输入值设置为div颜色 [英] how to set html color input values to div colors on click
本文介绍了如何在点击时将html颜色输入值设置为div颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果单击div,则html5颜色输入值应设置为单击的div颜色和背景颜色值.
If div is clicked, html5 color inputs values should set to clicked div color and background color values.
我尝试过代码
$(function() {
$("#changeMe").on('click', function() {
$('#designer-javascript-color').val($(this).css("color"));
$('#designer-javascript-backcolor').val($(this).css("background-color"));
});
});
Selected item color:
<input type="color" id="designer-javascript-color" />
<br>Selected item background color:
<input type="color" id="designer-javascript-backcolor" />
<br/>
<div id="changeMe" style='color:white;background-color: blue'>
click here</div>
在单击我后,两个输入均仍为黑色. 如何解决这个问题,使输入中出现白色和蓝色?
After clicking in click me both inputs have still black colors. How to fix this so that white and blue colors apper in inputs ?
测试用例位于 http://jsfiddle.net/bpc2w43w/
推荐答案
在使用前将rgb值转换为十六进制:
Convert the rgb value to hex before to use it:
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")));
});
});
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
Selected item color: <input type="color" id="designer-javascript-color" />
<br>
Selected item background color:<input type="color" id="designer-javascript-backcolor" />
<br/>
<div id="changeMe" style='color:white;background-color: blue'>
click here</div>
这篇关于如何在点击时将html颜色输入值设置为div颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文