有没有一种方法可以检查元素的父元素并找到第一个设置了CSS背景的元素,然后返回背景值?
类似于:
var background = $('element').parents().has(css('background'));更新:这是我现在使用的代码:
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);
};发布于 2010-02-11 03:13:54
如果没有设置,获取它将产生一个空字符串。因此,
var bg = ('element').parents().filter(function() {
return $(this).css('background').length > 0;
}).eq(0)编辑
一些研究表明,根据浏览器的不同,css('background')将始终生成空字符串或undefined。css('background-color')将正确地返回手头元素的颜色;但每个浏览器的值也不同,所以测试起来很麻烦(例如,IE中的transparent,火狐/chrome中的rgba(0,0,0,0),这两种都是指定透明的准确方法)。
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');
};发布于 2010-02-11 03:13:43
我认为正确的方法是检查.length属性。
在本例中,您需要遍历所有元素,并检查满足以下条件的第一个元素
.css('background').length != 0发布于 2010-02-11 03:13:59
$('selector').parents().filter(function() { return !!$(this).css('background'); });https://stackoverflow.com/questions/2239567
复制相似问题