【问题标题】:CSS transition not applied to max-height switching on UL listCSS 过渡不适用于 UL 列表上的最大高度切换
【发布时间】:2017-05-25 14:31:37
【问题描述】:

当我切换无序列表的最大高度时,我无法确定为什么没有应用指定的转换。切换是通过在 UL 上切换类来完成的。我尝试将过渡放在最大高度类中,但无济于事。我创建了一个working example on JSFiddle,下面提供了完整的代码。提前感谢您的帮助。

<!DOCTYPE html>
<html lang=en>
<head>
    <title>Transition Problem</title>
<style>
.nav ul {
    overflow: hidden;
    transition: max-height 2s;
    -webkit-transition: max-height 2s;
    white-space: normal;
}

.max-height-150 {
    max-height: 150px;
}

.max-height-none {
    max-height: none;
}
</style>
</head>
<body>
<p>The JavaScript switches the class correctly, and the height of the UL switches as expected, but the transition is not applied.</p>
<button>SWITCH CLASS</button>
<nav class="nav">
    <ul class="max-height-150">
        <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>
        <li>Item 15</li>
        <li>Item 16</li>
        <li>Item 17</li>
        <li>Item 18</li>
        <li>Item 19</li>
    </ul>
</nav>
<script>
// Select the button:
var button = document.getElementsByTagName('button')[0];

// Toggle between the two max-height classes when the button is clicked:
var buttonClickListener = function (e) {
    var navUl = document.querySelectorAll('.nav ul')[0];
    if (navUl.classList.contains('max-height-150')) {
        navUl.classList.remove('max-height-150');
        navUl.classList.add('max-height-none');
    } else {
        navUl.classList.add('max-height-150');
        navUl.classList.remove('max-height-none');
    }
    e.preventDefault();
};

// Add a click listener on the button and register the toggle function on it:
if (button.addEventListener) {
    button.addEventListener('click', buttonClickListener, false);
} else if (button.attachListener) {
    button.attachEvent('click', buttonClickListener);
}
</script>
</body>
</html>

【问题讨论】:

    标签: javascript css html-lists transition nav


    【解决方案1】:

    很遗憾,您无法从设置的最大高度转换为无(或自动或 100% 等)。您只能在设定的数字之间转换。尝试将新的最大高度设置为您认为它将具有的最大值,并且它应该按照您想要的方式工作。

    .max-height-none {
        max-height: 350px;
    }
    

    更新小提琴:https://jsfiddle.net/07cgn26r/1/

    【讨论】:

    • 谢谢!唯一的问题是从较大的最大高度到较小的最大高度的过渡的开始有一个“延迟”,实际上是花费时间覆盖元素的实际高度和指定的最大高度之间的差异。 (例如,尝试 max-height: 10000px 而不是 350px)。有没有办法用 JavaScript 动态添加最大高度(到真正的全高)并仍然获得过渡效果?
    猜你喜欢
    • 2021-12-07
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2019-10-12
    • 2013-02-12
    • 1970-01-01
    相关资源
    最近更新 更多