如何inheritance祖父母CSS而不是父?
我觉得这是不可能的,但我想我还是会问。
//body uses 'back' background //div1 uses 'front' background //child1: no backgrounds, so shows 'front' background
- 我的
body
元素使用背景图像。 (我称之为背景背景图片) -
div1
使用不同的背景图像(我将其称为front
背景图像),因此front
背景图像覆盖主背景图像。 - div1包含一个不使用任何背景图像的子div
child1
,因此它只显示其父级的背景图像,即它显示front
背景。
我希望child1
使用body
的背景而不是其父div1
的背景。 由于背景背景的本质(它是绘图,而不是重复的图案),我不能只将背景图像应用于child1
。 我实际上需要一种方法在div1
的背景中创建一个洞,以便child1
将back
背景图像作为其背景,而不是其父级的背景。
所以我的问题是:div有没有办法inheritance祖父母的背景,而不是父母的背景?
如果使用CSS无法做到这一点,我会接受javascript解决方案。
这将是使用javascript和jQuery:
CSS
body { background: url("Background 1"); } #div1 { background: url("Background 2"); } #child1 { background: url("Background 1"); }
JS
$(function() { function positionBackground() { var myChild1 = $("#child1"); myChild1.css({ backgroundPosition : "-" + myChild1.offset().left + "px -" + myChild1.offset().top + "px" }); } positionBackground(); $(window).resize(positionBackground); });
这是小提琴: http : //jsfiddle.net/gMK9G/
我不认为你能够改变样式的inheritance方式,也就是说,你真的不需要。
这有点粗糙,但你可以在身体上使用相同的图像,就像你在身体上使用一样,只需使用背景定位来排列它。
工作实例
body { background: url("Background 1"); } #div1 { background: url("Background 2"); } #child1 { background: url("Background 1"); background-position: 0px -125px; /* adjust as needed */ }
更新 DOM中的元素无法共享相同的背景图像,您可以应用背景图像并将它们精确定位,使其看起来像它们,但实际上它是不可能的。
据我所知, 目前这是不可能的,因为css只有inheritance和inheritance“父级”的“inheritance”,没有办法自定义。 当然javascript可以很容易地做到这一点,我将只提供一个jQuery示例,因为你有jquery标签。
$('.inherit-grandparent').each(function( element ) { var $this = $(this), property = $this.attr('grandparent-property'), value = $this.parent().parent().css(property); if(property && value) $this.css(property, value); });
用法
演示: http : //jsfiddle.net/aKHfr/
因此,这不仅会解决您的问题,而且它是动态的,因此您可以在任何元素上使用它并请求任何属性。
更新:
这是一个jQuery插件版本,如果您愿意的话。
jQuery.fn.inheritGrandparent = function( property ) { var $this = $(this), value = $this.parent().parent().css(property); if(property && value) $this.css(property, value); };
用法:
$('#test').inheritGrandparent('background');
演示: http : //jsfiddle.net/aKHfr/2/
快乐的编码!