我创建了一个显示部分内容的列表,并通过触发器折叠起来。一切工作正常,只是当它崩溃时我无法通过CSS过渡使其正常工作。基本上,我在2个类之间切换并应用一个高度:100%
HTML
<div class="list">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
<li>Item 10</li>
<li>Item 11</li>
<li>Item 12</li>
<li>Item 13</li>
<li>Item 14</li>
</ul>
<span class="more-less"></span>
</div>
CSS
.list.expand {
height: 180px;
overflow: hidden;
}
.list.expand.open {
height: 100%;
padding-bottom: 20px;
}
JS
var list = $(".list");
$(".more-less").click(function() {
list.toggleClass("open closed");
});
我做了CODEPEN做一些测试。我认为这是一种特定的情况,需要特定的解决方案。我花了数小时尝试在Stackoverflow(CSS和JS)上找到的代码段,但没有成功。
均非CSS过渡:高度0.5s缓解;或.animate(height ...)似乎对我有用:/所以,任何帮助或线索将不胜感激:)谢谢
编辑:我忘记了重要信息:列表内容是动态加载(WP)的,因此这就是为什么我需要将高度设置为“ auto”的原因。
您是否尝试过向.list.expand添加过渡?
.list.expand {
height: 180px;
overflow: hidden;
-webkit-transition: height 2s; /* For Safari 3.1 to 6.0 */
-moz-transition: height 2s;
transition: height 2s;
}
由于this post,我终于找到了jQuery的解决方法。可能不是实现该目标的最佳方法,但它有效:p
var list = $(".list");
// Apply only if list height is taller than 100px
if (list.height() > 100) {
list.addClass("expand closed");
}
// First, set height to auto then memorize the height value in a variable,
// then set the height to 100px
list.css("height", "auto");
var listheight = list.css("height");
list.css("height", "100px");
// When click to the "more-less" trigger, toggle between "open" and "closed" class,
// then apply the correct height for each class
$(".more-less").on("click", function() {
list.toggleClass("open closed");
if (list.hasClass("open")) {
list.height(listheight);
}
if (list.hasClass("closed")) {
list.height(100);
}
});
CodePen上的DEMO HERE