2017-05-25 66 views
0

當我切換無序列表的最大高度時,我無法確定爲何不應用指定的轉換。切換是通過切換UL上的類來完成的。我試過把這個過渡放在最大高度的類中,但是無濟於事。我創建了一個working example on JSFiddle,並在下面提供了完整的代碼。預先感謝您的幫助。CSS轉換不適用於UL列表上的最大高度切換

<!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> 

回答

2

不幸的是,您不能從設置的最大高度轉換爲無(或自動或100%等)。您只能在設定的數字之間切換。嘗試將新的最大高度設置爲您認爲它將具有的最大值,並且它應該以您想要的方式工作。

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

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

+0

謝謝!唯一的問題是,從較大的最大高度到較小的最大高度的轉換的開始具有「延遲」,實際上是花費在覆蓋元素的實際高度和指定的最大高度之間的差異的時間。 (例如,嘗試最大高度:10000px而不是350px)。有沒有辦法用JavaScript動態添加最大高度(真正的全高),並仍然獲得過渡效果? – Tom

+0

當然,試試這個https://jsfiddle.net/07cgn26r/2/ –