Javascript 如何创建一个动态导航栏,当您到达某个位置时会跟随您
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10088243/
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 create a dynamic navigation bar which follows you when you reach certain location
提问by Alvis Chen
I want to create a navigation bar similar to this site's:
我想创建一个类似于本网站的导航栏:
http://www.mysupermarket.co.uk/#/shelves/top_offers_in_asda.html
http://www.mysupermarket.co.uk/#/shelves/top_offers_in_asda.html
Can anyone tell me how to create that navigation bar, which follows you as you scroll the page down, but not following you at the initial loading of page?
谁能告诉我如何创建导航栏,在您向下滚动页面时跟随您,但在页面初始加载时不跟随您?
When you access to the given website, try to scrolling down and you will understand what I am talking about. The navigation bar that consists of MY SHOP, OFFERS, IDEAS & LIFESTYLE, BAKERY and so-on...
当您访问给定的网站时,尝试向下滚动,您就会明白我在说什么。由我的商店、优惠、创意与生活方式、面包店等组成的导航栏...
I have really no idea what it's called. At least tell me what it's called, so I'll be able to search.
我真的不知道它叫什么。至少告诉我它叫什么,这样我就可以搜索了。
Here is the solution I've done
这是我完成的解决方案
window.onscroll = function(){
if(getScrollTop()>140) {
document.getElementById("menu").style.position="fixed";
} else {
document.getElementById("menu").style.position="";
}
}
function getScrollTop() {
if (window.onscroll) {
// Most browsers
return window.pageYOffset;
}
var d = document.documentElement;
if (d.clientHeight) {
// IE in standards mode
return d.scrollTop;
}
// IE in quirks mode
return document.body.scrollTop;
}
回答by Cengiz Can
Holding an element on same position can be achieved by fixed positionstyling.
If you want your navigation bar to stay on exact same location, position:fixed;
is enough. (At least non IE6)
可以通过固定位置样式来将元素保持在同一位置。如果您希望导航栏停留在完全相同的位置,position:fixed;
就足够了。(至少非 IE6)
You can find a working exampleand some details here
However, if you want your navigation bar to move from it's initial location to the top border of page as you scroll the page down, you must implement some JavaScript to catch page scroll event and move the <div>
accordingly.
但是,如果您希望在向下滚动页面时导航栏从其初始位置移动到页面的顶部边框,则必须实现一些 JavaScript 来捕获页面滚动事件并相应地移动<div>
。
See this questionfor an example on how to do that.
回答by Jof Arnold
Note: this won't work with the Android 2.3 browser; position:fixed
will not behave as expected - it kinda of temporarily attaches its position to the scrolling element before jumping back to the top.
注意:这不适用于 Android 2.3 浏览器;position:fixed
不会按预期运行 - 在跳回顶部之前,它会暂时将其位置附加到滚动元素。
回答by SandStormFlux
if you want you could just set the z-index to be a specific No. and that should work.
如果你愿意,你可以将 z-index 设置为一个特定的编号,这应该可以工作。
example z-index:100;
示例 z-index:100;