导航栏没有在正确的位置折叠

时间:2018-06-23 00:03:49

标签: javascript html css

我有一个导航栏折叠javascript方法,如果满足此条件,则折叠:

  // Collapse Navbar
 var navbarCollapse = function() {
 if ($("#mainNav").offset().top > 100) {
  $("#mainNav").addClass("navbar-shrink");
 } else {
  $("#mainNav").removeClass("navbar-shrink");
 }
};
// Collapse now if page is not at top
navbarCollapse();
// Collapse the navbar when page is scrolled
$(window).scroll(navbarCollapse);

这是我的导航栏的HTML代码:

<body id="page-top">

<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
  <div class="container">
    <a class="navbar-brand js-scroll-trigger" href="#page-top">Kristoffer Tølbøll</a>
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
      Menu
      <i class="fa fa-bars"></i>
    </button>
    <div class="collapse navbar-collapse" id="navbarResponsive">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item">
          <a class="nav-link js-scroll-trigger" href="#download">My Work</a>
        </li>
        <li class="nav-item">
          <a class="nav-link js-scroll-trigger" href="#features">My Skills</a>
        </li>
        <li class="nav-item">
          <a class="nav-link js-scroll-trigger" href="#contact">Contact</a>
        </li>
      </ul>
    </div>
  </div>
</nav>

我有另一个页面,我希望导航栏在某个点折叠,我是否可以通过设置某种if else条件来触发该事件以使其折叠?

this is the non collapsed version

Collapsed version

我如何做到这一点?

1 个答案:

答案 0 :(得分:1)

这样可以吗? 我将补全更改为$(window).scrollTop()

map
 var navbarCollapse = function() {
 console.log($(window).scrollTop())
 if ($(window).scrollTop() > 70) {
  $(".main-nav").addClass("navbar-shrink");
 } else {
  $(".main-nav").removeClass("navbar-shrink");
 }
};
// Collapse now if page is not at top
navbarCollapse();
// Collapse the navbar when page is scrolled
$(window).scroll(navbarCollapse);
body{
padding:0;
margin:0;
}
.content{
  widht:100%;
  min-height:800px;
  background-color:#4527a0;
  padding-top:150px;
}

.main-nav{
  width:100%;
  display:inline-block;
  vertical-align:top;
  height:70px;
  background:#8e24aa;
  position:fixed;
  left:0px;
  top:0px;
}
.main-nav.navbar-shrink{
  height:50px !important;
}

.marker{
width:200px;
height:200px;
background:#fff176;
}