显示 UL 的部分内容,然后随着过渡而折叠



我创建了一个列表,显示部分内容并使用触发器折叠。一切都运行良好,除了我无法在它折叠时与 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过渡:高度.5s轻松; 或.animate(height...(似乎对我有用:/因此,任何帮助或线索将不胜感激:)谢谢

编辑:我忘记了一个关键信息:列表内容是动态加载的(WP(,所以这就是为什么我需要将高度设置为"自动"。

我找到了更好的方法来实现这一目标,使用.scrollHeight

.JS

var list = $(".list");
// variable storing an integer corresponding to the scrollHeight pixel value of the element.
var fullHeight = list[0].scrollHeight+'px';
if (list.height() > 100) {
list.addClass("expand closed");
list.height(100);
}
$(".more-less").on("click", function() {  
if(list.hasClass("closed")) {
list.animate({
height: fullHeight
}, 200);
} else if (list.hasClass("open")) {
list.animate({
height: "100px"
}, 200);
}
list.toggleClass("open closed");
});

.CSS

.list.expand {
overflow: hidden;
}

在 CodePen 上演示

您是否尝试过向 .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;
}

多亏了这篇文章,我终于找到了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);
}
});

.CSS

.list.expand {
height: 180px;
overflow: hidden;
-webkit-transition: height .3s ease-in-out;
-moz-transition: height .3s ease-in-out;
transition: height .3s ease-in-out;
}

在 CodePen 上演示

相关内容

最新更新