jQuery:检查元素是否具有CSS属性 [英] jQuery: check if element has CSS attribute

查看:68
本文介绍了jQuery:检查元素是否具有CSS属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以检查父元素,并找到第一个具有CSS背景集的元素,然后返回该背景值?

Is there a way to check an elements parents and find the first one that has a CSS background set and then return that background value?

类似的东西:

var background = $('element').parents().has(css('background'));

更新: 这是我现在使用的代码:

UPDATE: This is the code I'm now using:

jQuery.fn.getBg = function(){
    var newBackground = this.parents().filter(function() {
        return $(this).css('background-color').length > 0;
    }).eq(0).css('background-color');
    $(this).css('background-color',newBackground); console.log("new background is: "+newBackground);
};

推荐答案

如果未设置,则将其获取将产生一个空字符串.因此 

If it's not set, fetching it will yield an empty string. Hence  

var bg = ('element').parents().filter(function() {
    return $(this).css('background').length > 0;
}).eq(0)

编辑

一些研究表明,css('background')总是 会生成一个空字符串或undefined,具体取决于浏览器. css('background-color')将正确返回当前元素的颜色;但每个浏览器的值也不同,因此测试起来很麻烦(例如,IE中的transparent,firefox/chrome中的rgba(0,0,0,0)都是指定透明性的准确方法).

Some research shows that css('background') will always yield an empty string, or undefined, depending on browser. css('background-color') will correctly return the color of the element at hand; but also different values for each browser, so it is troublesome to test (transparent in IE, rgba(0,0,0,0) in firefox/chrome, for instance, both being accurate ways of specifying transparent).

jQuery.fn.getBg = function() {
    return $(this).parents().filter(function() {
        // only checking for IE and Firefox/Chrome. add values as cross-browser compatibility is required
        var color = $(this).css('background-color');
        return color != 'transparent' && color != 'rgba(0, 0, 0, 0)';
    }).eq(0).css('background-color');
};

这篇关于jQuery:检查元素是否具有CSS属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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