简体   繁体   English

CSS背景颜色有效期

[英]CSS background colour validity

I am adding a div dynamically and adding background colors to these divs. 我正在动态添加一个div并向这些div添加背景色。 The background color values are coming from the backend, so one div for each colour is added and its background colour is set to that colour. 背景颜色值来自后端,因此为每种颜色添加了一个div ,并将其背景颜色设置为该颜色。 But if some colour that is not valid for CSS background color property comes through, it shows as a white background. 但是,如果出现了一些不适用于CSS背景颜色属性的颜色,则它将显示为白色背景。

For example 'Leopard' colour. 例如“豹”色。 Is there any way to validate colous and not add the div if the color is not a valid background colour? 如果颜色不是有效的背景色,有什么方法可以验证colous而不添加div

I would absolutely avoid using named colours (eg. red, white, etc...) while using instead the standard hex declaration, eg: 我绝对避免使用命名的颜色(例如红色,白色等),而使用标准的十六进制声明,例如:

#FF0000 = #F00 = red
#000000 = #000 = black
#ffffff = #fff = white
#ac25B1 = some other *unnamed* colour

This way, you could easily check that the string is a valid HEX string, either 6 or 3 character long. 这样,您可以轻松地检查字符串是否为有效的十六进制字符串,长度为6或3个字符。

Make a list from the W3 Specifications . 列出W3规格

Then check to see if your color is in that list. 然后检查您的颜色是否在该列表中。 Here is an example. 这是一个例子。

colors = ['lime', 'orange', 'pink'];

if (colors.indexOf(the_color) >= 0) {
    // Set background
}

I think you could re-use this question 's solution. 我认为您可以重用此问题的解决方案。

It involves a jQuery script that checks if the submitted color really produces RGB values. 它涉及一个jQuery脚本,该脚本检查提交的颜色是否真的产生RGB值。 I'm copy-pasting it. 我正在复制粘贴。

colorToTest = 'lime'; // 'lightgray' does not work for IE

$('#dummy').css('backgroundColor', 'white');
$('#dummy').css('backgroundColor', colorToTest);
if ($('#dummy').css('backgroundColor') != 'rgb(255, 255, 255)' || colorToTest == 'white') {
    alert(colorToTest+' is valid');
}

Here's how it works: First, the colorToTest variable is set to the color you wish to validate; 它是这样工作的:首先,将colorToTest变量设置为您要验证的颜色; Then, the background of the target div (#dummy in this case) is set to white via jQuery; 然后,通过jQuery将目标div的背景(在本例中为#dummy)设置为白色; At last, the background of the target div is set to colorToTest . 最后,将目标div的背景设置为colorToTest If the color is still white, and colorToTest is not White, the backend color is not valid. 如果颜色仍然是白色,并且colorToTest不是白色,则后端颜色无效。

However, since an unvalid color won't produce any layout, you could just set the div background to white and then apply the backend color. 但是,由于无效的颜色不会产生任何布局,因此您可以将div背景设置为白色,然后再应用后端颜色。 If it's vaild, it will change. 如果有效,它将改变。 You could however use the above script to validate it, if you wish. 但是,您可以根据需要使用上述脚本进行验证。

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

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