检测元素是否指定了背景?

时间:2012-11-07 22:01:02

标签: javascript jquery html css

我试图确定某个元素是否明确设置了背景。我想我可以检查是否设置了.css('background') *,但是,它在浏览器之间是不一致的。例如,chrome显示没有背景设置为

的元素
background: rgba(0, 0, 0, 0) none repeat scroll 0% 0% / auto padding-box border-box
background-color: rgba(0, 0, 0, 0)
background-image: none

而IE8显示

background: undefined
background-color: transparent
background-image: none

(测试用例here

*(在jQuery中获取渲染样式不支持CSS的简写属性)

没有处理每个单独的案例是否有更好的方法来检测这个?

4 个答案:

答案 0 :(得分:3)

临时元素方法

这不是理想的,但你可以在js启动时创建一个临时元素,将其插入隐藏在文档中的某个地方(因为如果你没有为webkit浏览器获取空样式)然后读取该元素的默认背景样式集。这将为您提供基线值。然后,当您与真实元素进行比较时,如果它们不同,您就知道已经设置了背景。显然,这种方法的缺点是它无法检测您是否将背景专门设置为基线状态。

var baseline = $('<div />').hide().appendTo('body').css('background');

var isBackgroundSet = ( element.css('background') != baseline );

如果你想避免在元素上使用可能的全局样式,那会破坏系统,即:

div { background: red; }

...您可以使用以下代码,但我怀疑它是否能在旧浏览器中运行良好:

var baseline = $('<fake />').hide().appendTo('body').css('background');

背景

我花了一些时间处理类似的问题 - 尝试在设置为百分比时从元素获取原始宽度值。这比我想象的要复杂得多,最后我使用了类似的临时元素解决方案。正如Rene Koch所做的那样,我也期望getComputedStyle方法可以正常工作......真的很烦人,但事实并非如此。试图检测源CSS世界和运行时CSS世界之间的差异是一件困难的事情。

答案 1 :(得分:1)

这应该有效:

function isBGDefined(ele){
    var img = $(ele).css('backgroundImage'),
        col = $(ele).css('backgroundColor');

    return img != 'none' || (col != 'rgba(0, 0, 0, 0)' && col != 'transparent');
};

DEMO

我没有费心去测试background属性,因为最后它会更改backgroundImage和/或backgroundColor的计算样式。

以下是针对您的测试用例运行的代码(添加了另一个代码):http://jsfiddle.net/WG9MC/4/

答案 2 :(得分:0)

这篇文章解释了如何: http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/

function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}

答案 3 :(得分:0)

使用@pebbl建议的方法,我编写了一个小的jQuery函数hasBack(),以确定元素是否具有其背景集。

$.fn.hasBack = function()
{
    var me = $.fn.hasBack;
    if(!me.cache)
    {
        // get the background color and image transparent/none values
        // create a temporary element
        var $tmpElem = $('<div />').hide().appendTo('body');
        $.fn.hasBack.cache = {
            color: $tmpElem.css('background-color'),
            image: $tmpElem.css('background-image')
        };
        $tmpElem.remove();
    }
    var elem = this.eq(0);
    return !(elem.css('background-color') === me.cache.color && elem.css('background-image') === me.cache.image);
}

这是在Chrome v22,Firefox v15,Opera 12.1,IE9,IE9中测试设置为浏览器模式9 compat,9,8,7和怪癖模式。

测试用例here

相关问题