javascript 滚动时如何在浏览器顶部制作粘性菜单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21513843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a sticky menu at top of browser when scrolling?
提问by user3262259
Hello I am trying to make the menu below a sticky menu, I want it to stick to the top of the screen when the browser scrolls down to it. Below is the code I have so far but it is not working, can somebody please advice me where I have gone wrong.
您好,我正在尝试将菜单下方的菜单设置为粘性菜单,当浏览器向下滚动到它时,我希望它粘在屏幕顶部。下面是我到目前为止的代码,但它不起作用,有人可以告诉我哪里出错了。
Thank you
谢谢
html
html
</div>
<ul id="menu">
<li><a href="#">HOME</a></li>
<li><a href="#">TREATMENTS</a>
<ul>
<li><a href="#">Claim Kandi</a></li>
<li><a href="#">Claim Kandi2</a></li>
<li><a href="#">Claim Kandi3</a></li>
</ul>
</li>
<li><a href="#">ABOUT</a></li>
<li><a href="#">GALLERY</a></li>
<li><a href="#">CONTACT</a></li>
<li><a href="#">BOOKING</a></li>
javascript
javascript
<script type="text/javascript">$(document).scroll(function() {
var y = $(document).scrollTop(), header = $("#menu"); if(y >= 300)
{ header.css({position: "fixed", "top" : "0", "left" : "0"}); } else {header.css("position", "relative"); } });</script>
css
css
#menu {
display: inline-block;
min-width: 100%;
list-style:none;
border-top: 1px solid #ccc;
border-left: 1px solid #ccc;
border-bottom: 1px solid #ccc;
position: relative;
top:112px;
background-color:#666;
text-align: center;
}
回答by robjtede
I made a jsFiddle for it.
我为它制作了一个 jsFiddle。
I used the addClass()
and removeClass()
is a more elegant way of doing this.
我使用addClass()
和removeClass()
是一种更优雅的方式来做到这一点。
回答by Stelios Voskos
It seems that you haven't fixed the position on your #menu
. You have it relative
instead. Try this:
看来你还没有在你的#menu
. 你有它relative
。试试这个:
#menu {
display: inline-block;
position: fixed;
min-width: 100%;
list-style:none;
border-top: 1px solid #ccc;
border-left: 1px solid #ccc;
border-bottom: 1px solid #ccc;
top:112px;
background-color:#666;
text-align: center;
}