javascript 使用 HTML 和 CSS 修复滚动页面上的横幅
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17566958/
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
Fixed banner on scrolling page with HTML and CSS
提问by user2567824
I need to create a banner's placeholder that needs to scroll up together with a page until it reaches a browser's top edge and then it should be fixed at the top. When the page is scrolled down, the banner also needs to scroll with the page again. I'm not sure whether I'm clear enough so you can see the example at Watch Critic. You'll notice that the banner in the right column behaves just like I've described.
我需要创建一个横幅的占位符,它需要与页面一起向上滚动,直到它到达浏览器的顶部边缘,然后它应该固定在顶部。当页面向下滚动时,横幅也需要再次随页面滚动。我不确定我是否足够清楚,所以你可以在Watch Critic 上看到这个例子。您会注意到右栏中的横幅就像我描述的那样。
I don't have experience with JavaScript so can this be achieved with HTML and CSS only?
我没有使用 JavaScript 的经验,所以这只能用 HTML 和 CSS 来实现吗?
回答by Alvaro
Living example: http://jsfiddle.net/KXXhQ/
活生生的例子:http: //jsfiddle.net/KXXhQ/
You need to make use of the scroll
event of jQuery and then add a new class to your header in order to fix it:
您需要利用scroll
jQuery的事件,然后在您的标题中添加一个新类以修复它:
jQuery
jQuery
//by default, the static menu is hidden
var showStaticMenuBar = false;
//when scrolling...
$(window).scroll(function () {
//if the static menu is not yet visible...
if (showStaticMenuBar == false) {
//if I scroll more than 200px, I show it
if ($(window).scrollTop() >= 200) {
//showing the static menu
$('#header').addClass('fixed');
showStaticMenuBar = true;
}
}
//if the static menu is already visible...
else {
if ($(window).scrollTop() < 200) {
$('#header').removeClass('fixed');
//I define it as hidden
showStaticMenuBar = false;
}
}
});
CSS
CSS
#header{
display:block;
width: 100%;
height:50px;
background: #ddff00;
}
#header.fixed{
position:fixed;
top: 0; /*fixing it at the top*/
z-index: 999; /* over any other element*/
}
Living example: http://jsfiddle.net/KXXhQ/
活生生的例子:http: //jsfiddle.net/KXXhQ/