【问题标题】:Unable to add transition when width of navbar is changed with Javascript使用 Javascript 更改导航栏的宽度时无法添加过渡
【发布时间】:2021-08-21 12:29:12
【问题描述】:

我有一个导航栏,我正在更改单击复选框时的宽度。单击复选框时,我希望导航栏平滑过渡到更大的宽度。它似乎只是第一次在 sn-p 上工作。

这是我的代码:

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>

【问题讨论】:

  • transition 仅在您增加%px 中导航栏的宽度时才有效。例如; initial-width: 300px 和转换后的宽度 new-width: 100% 或任何 x%、xpx

标签: javascript html css navbar nav


【解决方案1】:

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

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>

希望它会起作用?

【讨论】:

    【解决方案2】:

    过渡仅适用于数值,因此您需要在 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>

    【讨论】:

      猜你喜欢
      • 2013-11-06
      • 1970-01-01
      • 2017-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多