尝试使用vanilla javascript使我的导航栏移动友好

时间:2018-04-16 12:54:24

标签: javascript jquery html css

我正在使用JavaScript,因此用户可以点击切换按钮(汉堡包),以便导航栏可以像移动导航栏一样在移动视图中下拉。像这样:enter image description here

但是,当我的导航栏处于移动视图中时,导航栏徽标会消失,但是当您单击切换(汉堡包)按钮时会显示该导航栏徽标。

enter image description here

我的HTML:

<!-- Top navigation -->
<div class="topnav" id="myTopnav">
  <a href="#center"class="active">Navbar Logo</a>
  <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">&#9776;</a>
  <!-- Centered link -->
  <div class="topnav-centered">
    <a href="#center">center</a>
  </div>

  <!-- Left-aligned links (default) -->
  <a href="#news">News</a>
  <a href="#contact">Contact</a>

  <!-- Right-aligned links -->
  <div class="topnav-right">
    <a href="#search">Search</a>
    <a href="#about">About</a>
  </div>

</div>

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

我的CSS:

body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

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

.topnav a {
  float: left;
  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: #4CAF50;
  color: white;
}

.topnav-centered a {
  float: none;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.topnav-right {
  float: right;
}

/* Responsive navigation menu (for mobile devices) */
@media screen and (max-width: 600px) {
  .topnav a, .topnav-right {
    float: none;
    display: block;
  }

  .topnav-centered a {
    position: relative;
    top: 0;
    left: 0;
    transform: none;
  }
}

.topnav .icon {
  display: none;
}

@media screen and (max-width: 600px) {
  .topnav .topnav-centered > a,
  .topnav .topnav-right > a,
  .topnav > a{
    display: none;
    }

  .nav-logo{
  }
  .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;
  }
}

我的JS:

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

指向我的codepen的链接是https://codepen.io/anon/pen/OvKjvK

1 个答案:

答案 0 :(得分:3)

隐藏徽标的 CSS - 具体来说,就是这个块;

@media screen and (max-width: 600px) {
  .topnav .topnav-centered > a,
  .topnav .topnav-right > a,
  .topnav > a{
    display: none;
    }

  .nav-logo{
  }
  .topnav a.icon {
    float: right;
    display: block;
  }
}

这条规则:

.topnav > a{
   display: none;
}

您的徽标在<a>范围内是.topnav,因此在小于600px宽度时会被隐藏。

您需要更加具体地使用CSS规则来解决此问题。