使用 HTML 和 JavaScript,我尝试创建一个列表,单击按钮时该列表会转换为视图,包括可滚动的内部容器,并在父 DIV 上使用最大高度转换。
但是,虽然父 div 平滑过渡,但过渡完成后内容会立即出现。似乎是在内部div溢出时发生的。
这是我一直在尝试的一个例子。
let visible = false;
function showHideList() {
const listContainerRef = document.getElementById('list-id');
if (!listContainerRef?.style?.maxHeight)
return;
listContainerRef.style.maxHeight = visible ? 0 + 'px' : 200 + 'px';
visible = !visible;
}
<button onclick="showHideList()" style="padding: 1rem; background: #2aabd2">Show / Hide</button>
<div id="list-id" style="transition: max-height 2s linear; overflow: hidden; max-height: 0;">
<div style="overflow: auto; max-height: 200px">
<div style="background-color: green">
<span style="display: block; background-color: red; padding: 0.5rem 0.75rem">Item 1</span>
<span style="display: block; background-color: red; padding: 0.5rem 0.75rem">Item 2</span>
<span style="display: block; background-color: red; padding: 0.5rem 0.75rem">Item 3</span>
<span style="display: block; background-color: red; padding: 0.5rem 0.75rem">Item 4</span>
<span style="display: block; background-color: red; padding: 0.5rem 0.75rem">Item 5</span>
<span style="display: block; background-color: red; padding: 0.5rem 0.75rem">Item 6</span>
</div>
</div>
</div>
看来问题是由
overflow: auto
引起的
let visible = false;
function showHideList() {
const listContainerRef = document.getElementById('list-id');
if (!listContainerRef?.style?.maxHeight)
return;
listContainerRef.style.maxHeight = visible ? 0 + 'px' : 200 + 'px';
visible = !visible;
}
span {
display: block;
background-color: red;
padding: 0.5rem 0.75rem
}
<button onclick="showHideList()" style="padding: 1rem; background: #2aabd2">Show / Hide</button>
<div id="list-id" style="transition: max-height 2s linear; overflow: hidden; max-height: 0;">
<div style="max-height: 200px">
<div style="background-color: green">
<span>Item 1</span>
<span>Item 2</span>
<span>Item 3</span>
<span>Item 4</span>
<span>Item 5</span>
<span>Item 6</span>
</div>
</div>
</div>