简体   繁体   中英

CSS background colour validity

I am adding a div dynamically and adding background colors to these divs. 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. But if some colour that is not valid for CSS background color property comes through, it shows as a white background.

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?

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.

Make a list from the W3 Specifications .

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. 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; Then, the background of the target div (#dummy in this case) is set to white via jQuery; At last, the background of the target div is set to colorToTest . If the color is still white, and colorToTest is not White, the backend color is not valid.

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. If it's vaild, it will change. You could however use the above script to validate it, if you wish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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