子div不继承父不透明度

时间:2013-08-21 15:43:22

标签: jquery css jquery-animate

<div class="notice_container" id="showMe">
    <div class="notice">some notice!</div>
</div>

JSFiddle here. (点击“运行”查看动画)

我需要.notice不要继承其父CSS不透明度。请注意,不透明度的jQuery动画分配为.notice_container

$('#showMe').css({
    "opacity": 0,
    "display": "block"
}).animate({
    opacity: .7
}, 1200)

为什么.notice会继承不透明度?如果我将它放在容器外面,它将失去淡入效果。我想看到红色的盒子完全不透明,黑色的容器很透明:有可能吗?怎么样?

非常感谢。


不工作的解决方案 - 这将解决inhert问题,但jQuery无法为其设置动画。

$('#showMe').css({
    backgroundColor: "rgba(0, 0, 0, 0)",
    "display": "block"
}).animate({
    backgroundColor: "rgba(0, 0, 0, 1)"
}, 1200);

请参阅:http://jsfiddle.net/Bbw7r/1/

3 个答案:

答案 0 :(得分:2)

我认为不可能不将元素的不透明度应用于其某些内容。你可以做的是复制包含元素,如下所示:

<div class="notice_container" id="showMe"></div>
<div class="notice_wrapper" id="showMeWrapper">
    <div class="notice">some notice!</div>
</div>

#showMe#showMeWrapper具有相同的尺寸和相同的位置,但保留showMeWrapper没有任何样式(透明背景,没有边框等)。仅为#showMe元素设置动画。如果您希望为尺寸或位置更改设置动画,请为它们设置动画。

答案 1 :(得分:1)

在这里,我根据我原来的绝对定位做了一个快速的样本:

  

http://jsfiddle.net/Bbw7r/5/

你工作的复杂程度不高。

<div class="notice_container handle" id="showMe"></div>
<div class="notice handle">some notice!</div>

$('.handle').show().delay(500).fadeTo('slow', 0.7);

(延迟只是让你看看发生了什么)

已更新:我错过了这个队列:

$('.handle').show().animate({opacity: .7}, {queue: false, duration: 1200});
$('.notice').animate({opacity: 1}, {queue: false, duration: 1200});

答案 2 :(得分:0)

不透明度属性 - 根据我的经验,以及某些信息,(例如:http://www.w3schools.com/cssref/css3_pr_opacity.asp) - 始终是继承的。

想一想:你想让一些元素半透明,并使它的不透明度= 0.5,你期望看到什么?从逻辑上讲,所有元素都是半透明的。否则你必须使其中的每个项目都是半透明的。

因此,您的示例有两个解决方案:

  1. 您可以将notice_container设置为不透明度:1(100%不透明度),但设置半透明背景色,如下所示:

    .notice_container
    {
        background-color: rgba(0, 0, 0, 0.5); /* semi-transparent black color */
    }
    
  2. 这种颜色的动画可以通过jQuery-UI实现(它允许动画颜色属性,但我没有测试它)

    1. 我正在使用其他方法:我的背景和通知块放在一个级别,而不是嵌套。像这样:

      <style>
      /* Style for shadow */
      .notice_shadow
      {
        position:fixed;
        z-index:9000;
        left:0px; right:0px; top:0px; bottom:0px;
        background: black;
        opacity:0.7;
        display:none;
      }
      /* Style for notice itself */
      .notice
      {
        position:fixed;
        z-index:9001;
        left:50%; top:50%; /* centering notice in the center of the screen */
        width:200px;
        height:100px;
        margin-left:-100px; /* the second part of parameters used for centering*/
        margin-top:-50px;
        background: red;
        color:white;
        display:none;
      }
      </style>
      <script>
      $(function(){
         $('.notice').fadeIn(1000);
         $('.notice_shadow').fadeIn(1000);
      });
      </script>
      <div class='notice_shadow'></div>
      <div class='notice'>Hello, this is a notice!</div>
      
    2. 尝试一下,也许我会更简单。

      顺便说一下,如果你想要制作简单的“模态”注意事项 - 可以使用很多实现,例如https://github.com/samdark/the-modal(不是我自己的,只是一个好的实现)