5

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

<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>
  • 我的body元素使用背景图像。(我称之为back背景图)
  • div1使用不同的背景图像(我称之为front背景图像),因此front背景图像覆盖了主背景图像。
  • div1 包含一个child1不使用任何背景图像的子 div,因此它只显示其父级的背景图像,即显示front背景。

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

所以我的问题是:有没有办法 div 可以继承其祖父母的背景,而不是其父母的背景?

如果 CSS 无法做到这一点,我愿意接受 javascript 解决方案。

4

4 回答 4

2

这将使用 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/

于 2013-08-31T04:20:29.007 回答
0

更新2 DOM 中的元素不能共享相同的背景图像,您可以应用背景图像并准确定位它们,使其看起来像它们,但实际上这是不可能的。

据我所知,这目前是不可能的,因为 css 只能从它的父母那里继承和继承“继承”,并且没有办法定制它。当然 javascript 可以很容易地做到这一点,我将提供一个 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);
}); 

用法

<div class="inherit-grandparent" grandparent-property="background"></div>

演示: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/

快乐编码!

于 2013-08-31T02:36:11.067 回答
0

我认为你不能改变继承样式的方式,也就是说,你不应该真的需要。

这有点粗糙,但您可以在子 div 上使用与在 body 上使用相同的图像,然后使用背景定位来对齐它。

工作示例

body {
    background: url("Background 1");
}
#div1 {
    background: url("Background 2");
}
#child1 {
    background: url("Background 1");
    background-position: 0px -125px; /* adjust as needed */
}
于 2013-08-31T02:39:22.477 回答
0

我的 HTML:

  <div class="p1">
       <div class="p2">
         <div class="p3">
           GandSOn
         </div>
       </div>
    </div>

我的CSS:

    .p1 {
disapley: flex;
}

.p2{
display:inherit;
}

.p3 {
display:inherit;
}
于 2021-04-28T07:55:16.193 回答