有没有办法检查元素父级并找到第一个具有CSS背景设置然后返回该背景值的方法?
就像是:
var background = $('element').parents().has(css('background'));
Run Code Online (Sandbox Code Playgroud)
更新:这是我现在使用的代码:
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);
};
Run Code Online (Sandbox Code Playgroud)
Dav*_*und 47
如果未设置,则获取它将产生空字符串.于是
var bg = ('element').parents().filter(function() {
return $(this).css('background').length > 0;
}).eq(0)
Run Code Online (Sandbox Code Playgroud)
编辑
有研究表明,css('background')将始终产生一个空字符串,或者undefined,根据浏览器.css('background-color')将正确返回手头元素的颜色; 但每个浏览器也有不同的值,因此测试很麻烦(例如,transparent在IE中,rgba(0,0,0,0)在firefox/chrome中,两者都是指定透明的准确方式).
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');
};
Run Code Online (Sandbox Code Playgroud)
我相信正确的方法是检查.length属性.
在您的情况下,您需要遍历所有元素并检查第一个遇到的元素
.css('background').length != 0
Run Code Online (Sandbox Code Playgroud)
$('selector').parents().filter(function() { return !!$(this).css('background'); });
Run Code Online (Sandbox Code Playgroud)