浮动菜单,如何将菜单粘贴到顶部?

时间:2017-10-27 14:12:06

标签: javascript jquery css

我对js相对较新,并且使用浮动菜单进行斗争。

这就是我的js代码的样子

$(function(){
 console.log('jest');
 $(window).scroll(function(event){
  console.log($('#menu').offset().top, $(this).scrollTop());
    if ($('#menu').offset().top <= $(this).scrollTop()+$(window).height()) {
                 $('#menu').addClass("fixed");
       } else {
           $('#menu').removeClass("fixed");
       }
  });
});

当达到顶部时,正确添加fixed类。

我的问题是: 我应该在fixed课程内做些什么来使菜单贴在顶部?

2 个答案:

答案 0 :(得分:0)

.fixed{
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
}

答案 1 :(得分:0)

很简单的“位置:粘性”..

brand {
  display: block;
  background-color: pink;
  padding: 10px;
  font-size: 20pt;
}

header {
  background-color: yellow;
  border: 2px solid black;
  padding: 10px;
  position: sticky;
  top: 0;
}

section {
  background-color: silver;
  padding: 10px;
}

body {
 padding: 0;
 margin: 0;
}
<brand>
<div>This is our branding,.  It can scroll away.</div>
<small>for all your header needs,.. </small>
</brand>

<header>
This is the header
</header>
<section>
Our othe stuff can go in here.<br><br><br><br><br><br><br><br><br><br>
Scroll down<br><br><br><br><br><br>
Even further<br><br><br><br><br>
A little bit more<br><br><br><br><br>
Ok I'm bored now.
</section>

<header>
This is repeated, see how the header takes over
</header>
<section>
Our othe stuff can go in here.<br><br><br><br><br><br><br><br><br><br>
Scroll down<br><br><br><br><br><br>
Even further<br><br><br><br><br>
A little bit more<br><br><br><br><br>
Ok I'm bored now.
</section>