导航栏为什么不固定在顶部?

时间:2020-01-14 16:44:20

标签: javascript jquery

当我检查窗口宽度时,此代码有效。一旦添加了对窗口宽度的引用,该代码将不再起作用。我只希望导航栏固定在小于768像素的屏幕上。我对jQuery感到生疏,不胜感激。

$(document).ready(function() {
  var width = $(window).width();

  $(window).scroll(function() {
    if ($(width) < 768) {
      if ($(this).scrollTop() > 567) {
        $('.navbar').css('position', 'fixed').css('top', '0');
      } else {
        $('.navbar').css('position', 'relative');
      }
    } else {
      $('.navbar').css('position', 'relative');
    }
  })

  $(window).resize(function() {
    if ($(width) < 768) {
      if ($(this).scrollTop() > 567) {
        $('.navbar').css('position', 'fixed').css('top', '0');
      } else {
        $('.navbar').css('position', 'relative');
      }
    } else {
      $('.navbar').css('position', 'relative');
    }
  });
});

1 个答案:

答案 0 :(得分:2)

这里的主要问题是在不需要时将width放在jQuery对象中。只需在以下情况下直接使用width

if (width < 768)

话虽如此,您的代码可以通过使用CSS类和媒体查询来进行干燥和改进。试试这个:

jQuery(function($) {
  $(window).on('scroll resize', function() {
    $('.navbar').toggleClass('fixed', $(this).scrollTop() > 567);
  });
});
html,
body {
  height: 2000px;
  padding: 0;
  margin: 0;
}

.navbar {
  padding: 10px;
  background-color: #CCC;
}

@media only screen and (max-width: 768px) {
  .navbar.fixed {
    position: fixed;
    top: 0;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navbar">Navbar</div>

相关问题