如何继承祖父母CSS不是父代?

sam*_*old 5 javascript css jquery background background-image

我觉得这是不可能的,但我还是想问一下。

<body>                  //body uses 'back' background
<div id="div1">         //div1 uses 'front' background
   <div id="child1">    //child1: no backgrounds, so shows 'front' background
   </div>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)
  • 我的body元素使用背景图片。(我将其称为back背景图片)
  • div1使用其他背景图片(我将其称为front背景图片),因此front背景图片覆盖了主要背景图片。
  • div1包含一个子div child1,它不使用任何背景图像,因此它仅显示其父级的背景图像,即显示front背景。

我想child1使用body其父级的背景,而不是其父级的背景div1。由于back背景的性质(这是一幅图画,而不是重复的图案),我不能仅将back背景图像应用于child1。我实际上需要一种在div1的背景上打洞的方法,以便child1back背景图像作为背景,而不是其父级的背景。

所以我的问题是:div是否可以继承其祖父母的背景而不是其父母的背景?

如果CSS无法做到这一点,我欢迎使用javascript解决方案。

ced*_*d-b 2

这需要使用 javascript 和 jQuery:

CSS

body {
   background: url("Background 1");
}
#div1 {
   background: url("Background 2");
}
#child1 {
   background: url("Background 1");
}
Run Code Online (Sandbox Code Playgroud)

JS

$(function() {

  function positionBackground() {

     var myChild1   = $("#child1");
     myChild1.css({
        backgroundPosition : "-" + myChild1.offset().left + "px -" + myChild1.offset().top + "px"
     });
  }

  positionBackground();

  $(window).resize(positionBackground);
});
Run Code Online (Sandbox Code Playgroud)

这是小提琴:http://jsfiddle.net/gMK9G/