javascript-类更改时的CSS过渡

我正在尝试使用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>

解决方法:

您需要在转换按钮CSS之前定义宽度:

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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。