如何动画响应式菜单

时间:2021-06-24 14:39:34

标签: javascript html css navbar transition

我有一个导航栏,当屏幕宽度较小时带有菜单图标。我做了动画,当我点击菜单图标时,它通过增加导航栏的最大高度来平滑地向下滚动,但我无法解决,向后做动画(当你再次点击菜单图标时)。 我尝试添加:过渡:最大高度 1s 缓出;到 .topnav{} 但它不起作用。

function responsiveNavbar() {
    var x = document.getElementById("responsiveNavBar");
    if (x.className === "topnav") {
      x.className += " responsive";
    } else {
      x.className = "topnav";
    }
  }
@media screen and (max-width: 600px) {
    .topnav.responsive {
        max-height: 400px;
        transition: max-height 1s ease-in;
    }
    *other*
}
@media screen and (max-width: 600px) {
    .topnav {
        max-height: 30px;
    }
    *other*
}
<div class="topnav" id="responsiveNavBar">
  <a>MODELS</a>
  <a>MOTORSPORT</a>
  <a>ABOUT</a>
  <div onclick="responsiveNavbar()">*working menu icon*</div>
</div>

1 个答案:

答案 0 :(得分:0)

看看这段代码

function myFunction() {
  var x = document.getElementById("myTopnav");
  if (x.className === "topnav") {
    x.className += " responsive";
  } else {
    x.className = "topnav";
  }
}
body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

.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;
}

.topnav a.active {
  background-color: #04AA6D;
  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;
  }
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>

<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);" class="icon" onclick="myFunction()">
    <i class="fa fa-bars"></i>
  </a>
</div>

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

工作代码源:https://codepen.io/aakash1282/pen/GRWVMwy

相关问题