javascript 向下滚动时更改标题 CSS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19939298/
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
Change header CSS upon scrolling down
提问by user2028856
I'm trying the achieve the same header fade in/fade out effect as this website: http://www.shopstyle.com/
我正在尝试实现与本网站相同的标题淡入/淡出效果:http: //www.shopstyle.com/
If you go to the website and scroll downwards, you'll see that the initial header is transparent but as you scroll down a certain number of pixels, the CSS switches to a solid background. Is this done via jquery/js or possible via CSS3?
如果您转到网站并向下滚动,您会看到初始标题是透明的,但是当您向下滚动一定数量的像素时,CSS 会切换到纯色背景。这是通过 jquery/js 完成的还是通过 CSS3 完成的?
Thank You
谢谢
回答by Explosion Pills
It's not possible via CSS alone since CSS cannot select the scroll top. It's very easy to do via javascript, though.
单独通过 CSS 是不可能的,因为 CSS 无法选择滚动顶部。不过,通过 javascript 很容易做到。
$(window).on("scroll", function () {
if ($(this).scrollTop() > 100) {
$("#header").addClass("not-transparent");
}
else {
$("#header").removeClass("not-transparent");
}
});
回答by Ennui
Use jQuery Waypointsplugin to trigger a class change on the header
at a specific scroll position/offset. There is even an extension of Waypoints specifically for this purpose (sticky elements) here. You can animate it either with CSS3 transitions/animations or jQuery UI class change animations.
使用jQuery Waypoints插件header
在特定滚动位置/偏移处触发类更改。甚至有路点的专门用于此目的(粘元素)的延伸在这里。您可以使用 CSS3 过渡/动画或 jQuery UI 类更改动画为其设置动画。
From a site I made recently that has a sticky header which also animates similar to the site you linked, this is all the JS I used for that feature:
从我最近创建的一个站点中,该站点有一个粘性标题,该标题也与您链接的站点类似,这是我用于该功能的所有 JS:
$('.header-wrap').waypoint('sticky', {
stuckClass: 'stuck',
offset: -1
});
offset: -1
means the change is triggered once the top of the .header-wrap
element hits -1px
in relation to the window (so basically once the window is scrolled AT ALL - if you put -200
it would not fire until the window had been scrolled 200px).
offset: -1
意味着一旦.header-wrap
元素的顶部-1px
相对于窗口点击就会触发更改(所以基本上一旦窗口滚动了 - 如果你把-200
它放在窗口滚动 200px 之前它不会触发)。
The class stuck
change handles all of the transparency, animation, position etc.
类stuck
更改处理所有透明度、动画、位置等。
回答by meavo
A combination of javascript and CSS3 should do the trick. In essence what you need to do is listen to the $(window).scroll Event and at a certain y-offset, add a class (e.g. fill) to your header:
javascript 和 CSS3 的组合应该可以解决问题。本质上,您需要做的是侦听 $(window).scroll 事件并在某个 y 偏移量处,将一个类(例如填充)添加到您的标题中:
.header { transition: all 1s; }
.header.fill { background-color:rgba(0,0,0,.25); }