如何在响应式导航栏上为展开添加平滑过渡?

时间:2017-12-03 11:53:32

标签: javascript html css html5 css3

如果导航栏在移动视口上折叠,如何添加平滑过渡?我尝试将transition属性添加到某些类但到目前为止还没有成功。我试图使导航栏的行为与Bootstrap中的导航栏类似,如下例https://codepen.io/ScottMarshall/pen/JoGWEX所示。感谢您的关注和支持。

function myFunction() {
  var x = document.getElementById("myTopnav");
  if (x.className === "topnav") {
    x.className += " responsive";
  } else {
    x.className = "topnav";
  }
}
body {
  margin: 0;
}

.topnav {
  overflow: hidden;
  background-color: #333;
}

.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

.active {
  background-color: #4CAF50;
  color: white;
}

.topnav .icon {
  display: none;
}

@media screen and (max-width: 600px) {
  .topnav a:not(:first-child) {
    display: none;
  }
  .topnav a.icon {
    float: right;
    display: block;
  }
}

@media screen and (max-width: 600px) {
  .topnav.responsive {
    position: relative;
  }
  .topnav.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .topnav.responsive a {
    float: none;
    display: block;
    text-align: left;
  }
}
<div class="topnav" id="myTopnav">
  <a href="#home" class="active">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
  <a href="#about">About</a>
  <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">&#9776;</a>
</div>

<div style="padding-left:16px">
  <h2>Responsive Topnav Example</h2>
  <p>Resize the browser window to see how it works.</p>
</div>

1 个答案:

答案 0 :(得分:0)

要使用transition效果,您需要设置height属性。

如下所示添加height,当然您也需要设置transition

.topnav{
   overflow:hidden;
   ...
   height: 50px;
   transition: .5s;
}

@media ...
.topnav.responsive {
   ...
   height: 200px;
 }

....... TADA ~~:)