jQuery,如果背景色== [英] jquery if background color ==

查看:80
本文介绍了jQuery,如果背景色==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查元素的背景,这是我的代码.但这不起作用:

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');
     }
}

这是第二个:

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?

这是我的最新代码,但仍无法正常工作:

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');
                }
            }

推荐答案

来自jQuery .css()文档:

请注意,元素的计算样式可能与样式表中为该元素指定的值不同.例如,尺寸的计算样式几乎总是像素,但是可以在样式表中将它们指定为emexpx%.不同的浏览器可能会返回逻辑上相等但文本上不相等的CSS颜色值,例如#FFF#ffffffrgb(255,255,255).

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).

大多数浏览器返回rgb值,因此您可以编写代码:

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

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

基于指定的原因,以上代码段在某些浏览器中可能会失败.您可以考虑使用颜色转换库或创建一个临时元素并进行设置并获取它的background-color/color属性.

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.

一个简单的jQuery插件:

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);

用法:

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

这篇关于jQuery,如果背景色==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆