简体   繁体   English

如何获得小数点的背景色?

[英]How can i get background colour decimals?

I'm trying to read background color which i set in decimals eg rgb(44.9, 19.373737, 255) using this code 我正在尝试使用此代码读取以十进制设置的背景色,例如rgb(44.9,19.373737,255)

$("p").css("background-color") 

but when used it keeps rounding it into rgb(45, 19, 255) 但是在使用时会不断将其四舍五入为rgb(45,19,255)

all i want to achieve is to get it in decimals 我要实现的是将其以小数形式获得

This is the sample code: 这是示例代码:

<script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Background color = " + $("p").css("background-color"));
    });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p style="background-color:rgb(44.9, 19.373737, 255)">This is a paragraph.</p>


<button>Return background-color of p</button>

I'm fan of testing. 我很喜欢测试。

Let's pretend we don't know colours are made of integers and let's test: 假设我们不知道颜色是由整数组成的,然后进行测试:

Let's make 4 divs, one with your decimal values and 3 with red and green rounded up or down. 让我们做4格,一个用十进制值,三个用红色和绿色向上或向下取整。

Next let's verify the output using a photo app like photofilter 接下来,让我们使用诸如photofilter之类的照片应用来验证输出

https://jsfiddle.net/vgrtky7g/ https://jsfiddle.net/vgrtky7g/

The first div don't show in jsfiddle, don't show in chrome but shows in firefox and edge which is a good enough warning. 第一个div不在jsfiddle中显示,不在chrome中显示,但在firefox和edge中显示,这是一个很好的警告。

If you run the code in firefox you will get : 如果您在firefox中运行代码,您将获得:

#2D13FF for both rgb(44.9, 19.373737, 255) and rgb(45, 19, 255) which means firefox was nice enough to round to the nearer integer. 对于rgb(44.9, 19.373737, 255)rgb(45, 19, 255) rgb(44.9, 19.373737, 255)均为#2D13FF ,这意味着firefox足以将其舍入到更接近的整数。

Don't rely on browser kindness and use integers ! 不要依赖浏览器的友善而使用整数!

RGB values are composed of three 8-bit integers (byte), for red, green and blue respectively ranges from 0 to 255. There are no fractional part allowed in those values. RGB值由三个8位整数(字节)组成,红色,绿色和蓝色的范围分别从0到255。这些值中不允许有小数部分。 Hence your style is not working. 因此,您的样式无效。

 $(document).ready(function(){ $("button").click(function(){ alert("Background color = " + $("p").css("background-color")); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h2>This is a heading</h2> <p style="background-color:rgb(44, 19, 255)">This is a paragraph.</p> <button>Return background-color of p</button> 

rgb() uses 8 bit color and 2^8 = 256. Therefore, you can only use integers ranging from 0 to 255 . rgb()使用8位颜色,2 ^ 8 =256。因此,只能使用0255 整数

The issue seems to be with your backend logic which is generating decimal point values. 问题似乎出在生成小数点值的后端逻辑上。 You can round off the values before storing or using it. 您可以在存储或使用它们之前四舍五入这些值。

I don't think the decimal values make any sense. 我认为十进制值没有任何意义。 rather round of it and use it in RGB. 相当圆,并在RGB中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM