【问题标题】:Multiline container unfolding animation多行容器展开动画
【发布时间】:2015-08-24 12:29:04
【问题描述】:

应该如何管理 CSS 多行容器(例如内容块或警报)展开动画?

http://plnkr.co/edit/Qq5fzeb3GBengviVNimC?p=preview

.alert {
  background: turquoise;
  color: white;
  padding: 10px;
  overflow: hidden;

    opacity: 0;
    max-height: 0;
}

body:hover .alert {
    display: block !important;
    opacity: 1;
  -webkit-transition: 2s;
  -moz-transition: 2s;
  -ms-transition: 2s;
  transition: 2s;
  max-height: 100px;
}

这里的问题是'多行',正如你所看到的,块高度不是一个固定值。

<div class="alert">Alert!<br>Alert!<br>Alert!</div>

虽然max-height: 100px 接近实际块高度,但它工作正常。如果max-height 较小,动画最后会出现锯齿,max-height: 9999px 会使过渡过快。

在 JS 中不计算精确高度可以做到吗?

【问题讨论】:

  • 据我所知,CSS 高度在没有固定尺寸的情况下无法平滑过渡。请参阅stackoverflow.com/questions/6089548/… 进行讨论。如果您使用 JS,则不必提前在 CSS 中指定高度,如该链接所示,或者如 TijnvW 在他们的回答中所展示的那样。

标签: html css


【解决方案1】:

计算高度确实可以在jQuery中完成,我做了以下来解决你的问题:

$("#out").html("Block height: " + $("#alert").height());
//solely for demonstration, you can delete this line

$("#alert").css('height','0px');

$('#alert').mouseover( function(){
    $("#alert").css('height', '58px');
});
$('#alert').mouseout( function(){
    $("#alert").css('height', '0px');
});
#alert {
  background: turquoise;
  color: white;
  padding: 10px;
  overflow: hidden;
  opacity: 0;
  //max-height: 0; this causes .height() to always display '0' so delete this here, and set this via jQuery

}

body:hover #alert {
	display: block !important;
	opacity: 1;
  -webkit-transition: 2s;
  -moz-transition: 2s;
  -ms-transition: 2s;
  transition: 2s;
 // max-height: 100px !important; set this via jQuery
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Hello!</p>
<div id="alert">Alert!<br>Alert!<br>Alert!</div>
<p>Hello again!</p>

<span id="out"></span>

【讨论】:

  • OP 在他们的问题中指定,“这可以在不计算 JS 中的确切高度的情况下完成吗?”
  • @Palpatim 是的,这是第二个问题。如果仅使用 CSS 是不可能的,我会接受 JS 的回答。但是这样的解决方案存在硬编码的高度,高度也可以在缩放、调整大小或改变块内容时改变。
  • 哎呀,完全忽略了“没有”这个词,对不起!不知道这是否可以在纯 CSS 中完成,所以我很好奇是否有人有其他解决方案
  • 不要认为任何人都知道纯 CSS 的解决方案,尽管块内容更改的问题可以通过表单字段元素的 .change() 来解决
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
相关资源
最近更新 更多