javascript - 样式显示时如何添加过渡?
问题描述
我有一个程序,当我单击某些东西时,我使用 JavaScript 使一个 div 出现,另一个消失:
<div id="first" class="active"> some content here </div>
<div id="second" class="inactive"> some content here </div>
<button onclick="change()"> button </button>
function change(){
document.getElementById("first").className="inactive";
document.getElementById("second").className="active"
}
.active{ display: block; }
.inactive{display: none; }
我想让它使一个 div 淡入,而另一个淡出。
我已经尝试过transition: ease 1s;
,transition: display 1s
并使用自定义转换,但是它们都没有奏效。
尝试点击这张卡片上的不同按钮- 文字淡入淡出。我要在这里达到那种效果。
我更喜欢只使用 HTML、CSS 和/或 JavaScript 的解决方案——试图让这个项目保持简单。
解决方案
使用opacity
:
function change() {
document.getElementById("first").className = "inactive";
document.getElementById("second").className = "active"
}
.active{
opacity:1;
}
.inactive{
opacity:0;
}
div{
transition:opacity 1s;
}
<div id="first" class="active"> some content here </div>
<div id="second" class="inactive"> some content here </div>
<button onclick="change()"> button </button>
要防止隐藏元素占用空间,请使用:
function change() {
const f1 = document.getElementById("first");
f1.style.opacity = "0";
setTimeout(() => {
f1.style.display = "none"
const f2 = document.getElementById("second");
f2.style.display = "block";
setTimeout(() => {
f2.style.opacity = "1";
}, 50);
}, 1000);
}
.active {
display: block;
opacity: 1;
}
.inactive {
display: none;
opacity: 0;
}
div {
transition: opacity 1s;
}
<div id="first" class="active"> some content here </div>
<div id="second" class="inactive"> some content here </div>
<button onclick="change()"> button </button>
推荐阅读
- oracle - 我必须在不使用条件语句的情况下在 Pl/SQl 中找到一个数字的回文
- javascript - 测试动态项目列表条件的最佳方法?
- javascript - 如何在 Vue+typescript 中为 Angular 创建 Web 组件?
- c++ - 使用 cusolverDnDpotrfBatched 得到不正确的结果
- visual-studio-code - 为 .code-workspace 文件指定默认的“打开工作区...”位置
- django - 如何使用 Supervisor(包括 Gunicorn 和 Nginx)设置多个 Django 应用程序?bind() to [::]:8090 失败(98:地址已在使用中)
- laravel - 如何检测电子邮件是否未送达收件人?(Gmail SMTP,传送失败)
- javascript - 如何迭代对象数组
- fullcalendar - 我在我的 vue 应用程序中使用 2 fullcalendar,当我点击日历时,我必须点击弹出窗口两次才能关闭它
- typescript - 打字稿:无法将 parseInt() 应用于 HTTP 请求标头中的字符串