使响应菜单变粘

时间:2019-09-17 16:28:24

标签: html css sticky

我正在尝试创建一个响应式粘滞菜单。我可以使粘性菜单起作用,也可以使响应菜单起作用(在移动设备上创建汉堡菜单),但是我不能使响应移动菜单变得粘滞!

您可以看到我要去的地方:https://www.cieh.org/responsive-sticky-menu-test/

有人可以帮忙吗?代码如下:

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



window.onscroll = function() {
  myFunction()
};

var myTopnav = document.getElementById("myTopnav");
var sticky = myTopnav.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    myTopnav.classList.add("sticky")
  } else {
    myTopnav.classList.remove("sticky");
  }
}
.topnav {
  overflow: hidden;
  background-color: #333;
  z-index: 1;
}

.topnav a {
  display: inline-block;
  color: #a5a7a8;
  text-align: center;
  padding: 7px 16px;
  text-decoration: none;
  font-size: 15px;
  font-weight: bold
}

.topnav a:hover {
  background-color: #880d53;
  color: white;
}

.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

.sticky+.content {
  padding-top: 60px;
}

.topnav .icon {
  display: none;
}

@media screen and (max-width: 600px) {
  .topnav a:not(:first-child) {
    display: none;
  }
  .topnav a.icon {
    float: right;
    display: inline-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 id="myTopnav" class="topnav" style="text-align: center;"><a href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> <a href="#about">About</a>
  <a class="icon" onclick="myFunction1()"> <span class="fa fa-bars"></span> </a>
</div>

2 个答案:

答案 0 :(得分:0)

使用position: sticky属性时可以添加一个粘性值。这是一个link,可以帮助您实现想要使用粘性的功能。如果只希望标题保持在顶部,则可以使用position: fixedposition: absolute。通常,如果您希望在向下滚动时将某些东西留在某个区域的顶部,则可以使用sticky

我只是将固定位置添加到该菜单,而将其打开始终固定在该位置。

@media(max-width: 600px) {
    #myTopnav { position: fixed; width: 100%;}
}

答案 1 :(得分:0)

  

但是我不能使响应式移动菜单变得很粘!

在正常状态下,标识为“ #myTopnav”的元素的类为“粘性”

enter image description here


当菜单打开时,通过按下“汉堡”按钮,“ stick”类消失了 enter image description here

即使您手动添加此类,另一个更具特异性的规则也会覆盖var==$0属性。

enter image description here