首页 > 解决方案 > 样式显示时如何添加过渡?

问题描述

我有一个程序,当我单击某些东西时,我使用 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 的解决方案——试图让这个项目保持简单。

标签: javascripthtmlcss

解决方案


使用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>


推荐阅读