【问题标题】:position:absolute element messes up fading of another位置:绝对元素搞砸了另一个的褪色
【发布时间】:2017-05-09 13:05:11
【问题描述】:

我正在尝试淡化文本,但它只是弹出到结束状态而不会在中间淡出(部分也有延迟)。

我正在使用 CSS 进行淡入淡出(opacity: 0/1transform: opacity),经过大量调试后,我发现这是由于下面完全不相关的 position: absolute 元素而发生的。这是一个小提琴:

var $root = $('.root');
$('#butt_fadetext').click(function(){
  $root.toggleClass('dermineyda');
});
$('#butt_hidefancy').click(function(){
  $root.toggleClass('nofancy');
});
.root {
  background-color: #b87988;
}

.container {
  transition: opacity 0.5s;
  opacity: 1;
  height: 100px;
}

.dermineyda .container {
  opacity: 0;
}

.inn {
  position: absolute;
  z-index: 1;
}

.unrelated {
  background-color: blanchedalmond;
  width: 100px;
  height: 30px;
  position: absolute;
  top: 0;
  left: 0;
}

.nofancy .unrelated {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="root">
  <div class="container">
    <div class="inn">text</div>
  </div>
  <div class="unrelated">fancy fx</div>
</div>
<input type="button" value="fade text" id="butt_fadetext" />
<input type="button" value="hide fancy fx" id="butt_hidefancy" />

【问题讨论】:

    标签: css css-position opacity fade


    【解决方案1】:

    我刚刚了解到,更改元素的 opacity 可以改变其在 stacking context 中的顺序:

    使用此属性的值不同于 1 会放置元素 在新的堆叠上下文中。

    解决方案

    我通过在堆叠上下文中强制其顺序向上来修复它。

    var $root = $('.root');
    $('#butt_fadetext').click(function(){
      $root.toggleClass('dermineyda');
    });
    $('#butt_hidefancy').click(function(){
      $root.toggleClass('nofancy');
    });
    .root {
      background-color: #b87988;
    }
    
    .container {
      transition: opacity 0.5s;
      opacity: 1;
      height: 100px;
      position: relative;
      z-index: 500;
    }
    
    .dermineyda .container {
      opacity: 0;
    }
    
    .inn {
      position: absolute;
      z-index: 1;
    }
    
    .unrelated {
      background-color: blanchedalmond;
      width: 100px;
      height: 30px;
      position: absolute;
      top: 0;
      left: 0;
    }
    
    .nofancy .unrelated {
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <div class="root">
      <div class="container">
        <div class="inn">text</div>
      </div>
      <div class="unrelated">fancy fx</div>
    </div>
    <input type="button" value="fade text" id="butt_fadetext" />
    <input type="button" value="hide fancy fx" id="butt_hidefancy" />

    【讨论】:

      【解决方案2】:

      嗯……重新发明代码是没有意义的。您正在使用 jquery,因此请使用 fadeToggle(...) 函数。

      【讨论】:

      • transform: opacity 是非常简单的 CSS imo。这不像是重新发明任何东西。此外,fadeToggle() 似乎不起作用 - 文本仍然“弹出”:jsfiddle.net/cmsd87gj
      • Yes。请理解为什么它不起作用:fadeToggle() 没有规避堆栈上下文的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 2011-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多