使用 Javascript 更改导航栏宽度时无法添加过渡

Unable to add transition when width of navbar is changed with Javascript

我有一个导航栏,我在单击复选框时更改宽度。单击复选框时,我希望导航栏平滑过渡到更大的宽度。它似乎只在第一次使用该代码段时起作用。

这是我的代码:

function change() {
  var nav = document.getElementById("navbar");
  var checkBox = document.getElementById("checkbox");
  if (checkBox.checked == true) {
    nav.style.width = "300px";
  } else {
    nav.style.width = "fit-content";
  }
}
nav {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 100px;
  height: 100%;
  transition: 0.3s;
  box-shadow: rgba(136, 165, 191, 0.26) 4px 2px 10px 0px, rgba(255, 255, 255, 0.8) -4px -2px 16px 0px;
}

nav input {
  margin: 10px;
  position: absolute;
  width: 50px;
  height: 50px;
  opacity: 0;
  cursor: pointer;
}
<nav id="navbar">
  <input onclick="change()" type="checkbox" name="" id="checkbox">
  <p>Home</p>
</nav>

过渡仅适用于数值,因此您需要相应地更改 else-case 中的宽度,例如更改为 50px。

function change(){
    var nav = document.getElementById("navbar");
    var checkBox = document.getElementById("checkbox");

    if(checkBox.checked == true){
        nav.style.width = "300px";


    } else{
        nav.style.width = "50px";
   
    }
}
nav{
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width:100px;
    height: 100%;
    transition: 0.3s;
    box-shadow: rgba(136, 165, 191, 0.26) 4px 2px 10px 0px, rgba(255, 255, 255, 0.8) -4px -2px 16px 0px;
}

nav input{
    margin: 10px;
    position: absolute;
    width: 50px;
    height: 50px;
    opacity: 0;
    cursor: pointer;
}
<nav id="navbar">
  
        <input onclick="change()" type="checkbox" name="" id="checkbox">
        
       <p>Home</p>
    </nav>

您可以在导航栏上使用 onClick 事件侦听器,而不是将 checkbox 与 JavaScript 一起使用。然后创建一个 class 例如 .expanded 并相应地切换 class。

const navbar = document.querySelector('.navbar');

navbar.addEventListener('click', (e) => {
  navbar.classList.toggle('expanded');
});
* {
  margin: 0;
  padding: 0;
  outline: 0;
  box-sizing: border-box;
}

.navbar {
  width: 100px;
  padding: 1rem;
  background-color: white;
  transition: width 250ms ease;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.25);
}

.navbar.expanded {
  width: 300px;
}
<nav class="navbar">
  <p>Navbar</p>
</nav>

希望它会起作用