如何获取元素的背景色代码?
console.log($(".div").css("background-color")); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="div" style="background-color: #f5b405"></div>
我想要的是
#f5b405
检查下面的示例链接,然后单击div以获取十六进制的颜色值。
var color = ''; $('div').click(function() { var x = $(this).css('backgroundColor'); hexc(x); console.log(color); }) function hexc(colorval) { var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); delete(parts[0]); for (var i = 1; i <= 3; ++i) { parts[i] = parseInt(parts[i]).toString(16); if (parts[i].length == 1) parts[i] = '0' + parts[i]; } color = '#' + parts.join(''); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='div' style='background-color: #f5b405'>Click me!</div>