CSS类变化时的过渡效果

4

我正在尝试使用JavaScript在元素添加或删除特定类时过渡width属性。如果我尝试在:hover上更改属性,则过渡效果正常,但如果我尝试通过添加或删除类来过渡它,则无法正常工作。我做错了什么?

function activate(number) {
  var bottom1 = document.getElementById("bottom-1");
  var bottom2 = document.getElementById("bottom-2");
  if (number === 1) {
    bottom1.classList.add("active");
    bottom2.classList.remove("active");
  } else {
    bottom2.classList.add("active");
    bottom1.classList.remove("active");
  }
}
body {
  display: flex;
  }
.container {
  position: relative;
  }
 .bottom-1 {
    position: absolute;
    bottom: 0px;
    right: 0px;
    height: 2px;
    background-color: red;
    transition: width 1s ease;
    }

 .bottom-2 {
    position: absolute;
    bottom: 0px;
    left: 0px;
    height: 2px;
    background-color: red;
    transition: width 1s ease;
    }
.active {
  width: 100%;
    }
<div class="container">
    <button onclick="activate(1)">Button 1</button>
    <div id="bottom-1" class="bottom-1 transition"></div>
</div>
<div class="container">
   <button onclick="activate(2)">Button 2</button>
   <div id="bottom-2" class="bottom-2 transition"></div>
</div>

1个回答

4

transition 之前,您需要在按钮的 CSS 中定义 width

function activate(number) {
  var bottom1 = document.getElementById("bottom-1");
  var bottom2 = document.getElementById("bottom-2");
  if (number === 1) {
    bottom1.classList.add("active");
    bottom2.classList.remove("active");
  } else {
    bottom2.classList.add("active");
    bottom1.classList.remove("active");
  }
}
body {
  display: flex;
  }
.container {
  position: relative;
  }
 .bottom-1 {
    position: absolute;
    bottom: 0px;
    right: 0px;
    height: 2px;
    width: 0%;
    background-color: red;
    transition: width 1s ease;
    
    }

 .bottom-2 {
    position: absolute;
    bottom: 0px;
    left: 0px;
    height: 2px;
    width: 0%;
    background-color: red;
    transition: width 1s ease;
    }
.active {
  width: 100%;
    }
<div class="container">
    <button onclick="activate(1)">Button 1</button>
    <div id="bottom-1" class="bottom-1 transition"></div>
</div>
<div class="container">
   <button onclick="activate(2)">Button 2</button>
   <div id="bottom-2" class="bottom-2 transition"></div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接