简体   繁体   English

粘性导航栏-不起作用

[英]Sticky navigation bar - not working

Question

I want the navBar to stick conditionally on scroll. 我希望navBar有条件地坚持滚动。 However there are bugs I can not quite diagnose, as I am new to jQuery. 但是,有些错误我无法完全诊断,因为我是jQuery新手。 What is preventing the nav bar from sticking conditionally on scroll? 是什么阻止导航栏有条件地粘在滚动条上?

The jQuery in the jsfiddle below will not run correctly, and after trying for awhile to make it work, I cannot seem to make it run. 下面的jsfiddle中的jQuery将无法正常运行,并且在尝试使它工作一段时间之后,我似乎无法使其运行。 I've looked at other examples of this but I'd rather not change the jQuery entirely until I know the reason that my code does not work. 我已经看过其他示例,但我不希望完全更改jQuery,直到我知道我的代码无法正常工作的原因。 I will not link the HTML as it full of Lorem Ipsum test text body. 我不会链接HTML,因为它充满了Lorem Ipsum测试文本正文。 It is found in the JSFiddle link. 在JSFiddle链接中可以找到它。

What is the error in the javascript that isn't making the navBar apply the sticky class? 没有使navBar应用粘滞类的javascript错误是什么?

Javascript Java脚本

var navTop = $(".nav").offset().top;

var stickyNav = function(){
  if ($(window).scrollTop() >= navTop){
    $(".nav").addClass(".sticky")
  } else {
    $(".nav").removeClass(".sticky")
  }
};

stickyNav();

$(window).scroll(function(){
    stickyNav();
};

CSS 的CSS

* {
  margin: 0;
  box-sizing: border-box;
}

.mainHeader {
  width: 100%;
  height: 20%;
  background-color: rgb(62, 65, 66);
  text-align: center;
  font-family: "Helvetica Nue";
}

.navigation {
  width 100%;
  height 10%;
  background-color: rgb(89, 127, 143);
  position: relative;
}

.sticky {
  position: fixed;
}

https://jsfiddle.net/11u1bj5j/ https://jsfiddle.net/11u1bj5j/

You have some bugs in your js code. 您的js代码中有一些错误。 Firstly, .nav should be nav since your <nav> element has a class of navigation . 首先, .nav应该是nav因为您的<nav>元素具有navigation类。 So, we'll grab it by the tag name instead. 因此,我们将改为通过标签名称来抓取它。 Secondly, .addClass() and .removeClass() don't need the period before the class name. 其次, .addClass().removeClass()不需要在类名之前加句号。

Here's the updated javascript: 这是更新的javascript:

var navTop = $("nav").offset().top;

var stickyNav = function(){
    if ($(window).scrollTop() >= navTop){
        $("nav").addClass("sticky");
    } else {
        $("nav").removeClass("sticky");
    }
};

stickyNav();

$(window).scroll(function(){
    stickyNav();
});

Here's an updated fiddle . 这是最新的小提琴

first of all you are adding/removing classes wrongly with jquery should be 首先,您使用jquery错误地添加/删除了类

.addClass("sticky") / .removeClass("sticky")

same with nav selection, there were some other small css problems too nav选择相同,也有一些其他小的CSS问题

here is working jsfiddle 这是工作jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM