繁体   English   中英

如何使用 Vanilla JavaScript 平滑过渡显示 div

[英]How to display a div with a smooth transition with Vanilla JavaScript

我在我的网站上有一个阅读更多选项来显示一些信息。

目前我的按钮像开/关开关一样切换 div 的显示属性。

我希望通过单击按钮平滑地向下扩展页面来显示整个 div,我尝试了一些带有过渡的组合,但我没有运气。 我知道转换不适用于 display 属性,任何想法如何最好只使用 CSS 和一个简单的函数来实现这一点?

 function seeMore() { const text = document.querySelector('#website-info-idea') const text2 = document.querySelector('#website-info-technical ') if (text.style.display && text2.style.display === 'block') { text.style.display = 'none' text2.style.display = 'none' } else { text.style.display = 'block' text2.style.display = 'block' } }
 #website-info-idea, #website-info-technical { text-align: center; display: none; transition: all 1s ease; }
 <a onclick="seeMore()" class="btn btn-secondary btn-md btn-custom">About this Website</a> <div class="col" id="website-info-idea">Idea</div> <div class="col" id="website-info-technical">Technical</div>

为了使 div 平滑扩展,您必须设置最终状态高度 - 而不是“自动” - 并且过渡必须包括高度的变化。

因此:

 function seeMore() { const text = document.getElementById('website-info-idea') const text2 = document.getElementById('website-info-technical') text.classList.toggle("show") text2.classList.toggle("show") }
 .col { opacity: 0; height: 0; overflow: hidden; transition: all 1s ease-in-out; } .col.show { opacity: 1; height: 23px; transition: all 1s ease-in-out; }
 <a onclick="seeMore()" class="btn btn-secondary btn-md btn-custom">About this Website</a> <div class="col" id="website-info-idea">Idea</div> <div class="col" id="website-info-technical">Technical</div>

像这样的东西

 function seeMore() { const text = document.getElementById('website-info-idea') const text2 = document.getElementById('website-info-technical') text.classList.toggle("show") text2.classList.toggle("show") }
 .col { transition: opacity 1s ease-out; opacity: 0; height: 0; overflow: hidden; } .col.show { opacity: 1; height: auto; }
 <a onclick="seeMore()" class="btn btn-secondary btn-md btn-custom">About this Website</a> <div class="col" id="website-info-idea">Idea</div> <div class="col" id="website-info-technical">Technical</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM