Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
884 views
in Technique[技术] by (71.8m points)

jquery if background color ==

I am trying to check for the background of an element, here is my code. But it doesn't work:

I tried two ways, here is the first:

function changeColor(field) {
     if(field.css('background-color','#ffb100')) {
          field.css('background-color','white');
     }
     else {
          field.css('background-color','ffb100');
     }
}

here is the second:

function changeColor(field) {
     if(field.css('background-color') === '#ffb100') {
          field.css('background-color','white');
     }
     else {
          field.css('background-color','ffb100');
     }
}

But neither worked! Any suggestions?

EDIT: This is my latest code, but it still is not working:

function changeColor(field) {
                if(field.css('background-color') == 'rgb(255, 255, 255)') {
                    field.css('background-color','ffb100');
                }
                else {
                    field.css('background-color','white');
                }
            }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From jQuery .css() documentation:

Note that the computed style of an element may not be the same as the value specified for that element in a style sheet. For example, computed styles of dimensions are almost always pixels, but they can be specified as em, ex, px or % in a style sheet. Different browsers may return CSS color values that are logically but not textually equal, e.g., #FFF, #ffffff, and rgb(255,255,255).

Most browsers return a rgb value, so you can code:

if (field.css('background-color') === 'rgb(255, 177, 0)') {
   // ...
}

The above snippet, based on the specified reason, may fail in some browsers. You can consider using a color conversion library or create a temporary element and set and get it's background-color/color property.

A simple jQuery plugin:

(function($) {
    $.fn.isBgColor = function(color) {
        var thisBgColor = this.eq(0).css('backgroundColor');
        var computedColor = $('<div/>').css({ 
            backgroundColor: color
        }).css('backgroundColor');
        return thisBgColor === computedColor;
    }
})(jQuery);

Usage:

if ( field.isBgColor('#ffb100') ) {
   // ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...