javascript - 扩大 UL 的过渡效应

标签 javascript html css transition

<分区>


想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post .

关闭 8 年前

如何在此扩展列表上添加过渡效果?

<div class="container">
    <div class="outerBG"> 
        <div class="innerBG">
            <h2 class="info">&#10148; Show text</h2>
            <ul id="infoContent" style="display:none">
                <li>TEST 1 TEST 1 TEST 1 TEST 1</li>
                <li>TEST 2 TEST 2 TEST 2 TEST 2</li>              
            </ul>
        </div>
    </div>
</div>

我正在使用 JavaScript 切换 UL 的显示:

function expand () {
    infoContent.style.display = infoContent.style.display === 'none' ? '' : 'none';
}

是否可以由此制作过渡效果?

jsfiddle:https://jsfiddle.net/mqy2c80u/

最佳答案

您不能使用 display: none 将元素设置为动画。

但是,您可以更新 expand 函数,将类从 open 更改为 close,如下所示:

JavaScript 更改:

function expand () {
    infoContent.className = infoContent.className === 'open' ? 'close' : 'open';
}

然后使用 max-height 应用 CSS 动画(如果动画 div 中的内容是动态的):

CSS 添加:

#infoContent {
    margin: 0; // Remove the margins
    overflow: hidden;
}

#infoContent.close {
    max-height: 0; // Set max height to zero
    transition: max-height 0.3s ease;
}

#infoContent.open {
    max-height: 300px; /* Set max height as big as you think it will ever go */
    transition: max-height 0.3s ease;
}

演示: JSFiddle

关于javascript - 扩大 UL 的过渡效应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30401002/

上一篇:javascript - 当与 attr 函数一起使用时,javascript 数组中的元素输出未定义而不是实际值

下一篇:html - CSS 表格单元格输入不占全宽

相关文章:

javascript - 文件 API、网络 worker 和 Chrome/Chromium

javascript - Google Apps 脚本可以逐行读取 txt 吗?

javascript - 处理 html 表单响应

html - 如何水平和垂直居中元素

css - 从嵌套 div 中选择偶数

jquery - 单击时展开相应的 ul

javascript - 如何将 Intercom.io JS 与 WordPress 和 Typeform 集成

javascript - 如何使 Angular 仅影响同一行的模型和范围

javascript - document.innerHTML 在 'DOMNodeInserted' 事件捕获函数中未定义

HTML/CSS Div 在浏览器调整大小时移动