如何使用 CSS 更改滚动背景?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17586162/
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 do I change my background on scroll using CSS?
提问by rob_towner
My website has THE PERFECT FULL PAGE BACKGROUND IMAGE. I grabbed the code for it from css tricks.
我的网站有完美的全页背景图片。我从css 技巧中获取了它的代码。
If you visit my siteyou can see it in action.
如果您访问我的网站,您可以看到它的实际效果。
What I'd like to know is, is there a way I can have this image change to a different image once you scroll a certain length?
我想知道的是,有没有一种方法可以在滚动一定长度后将此图像更改为不同的图像?
My aim is to have the same image but with a speech bubble coming out of the dogs mouth and I'm guessing 2 images will do this.
我的目标是拥有相同的图像,但从狗嘴里冒出一个气泡,我猜有 2 个图像可以做到这一点。
Is this possible to do in CSS only??????
这只能在 CSS 中实现吗??????
Here is the code I am currently using.
这是我目前使用的代码。
html {
background: url(http://robt.info/wp-content/uploads/2013/06/funny-kids-comic-animals.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
回答by gmo
As others already said, Nop, you can't only with CSS
, but a little js code
can do it for you.
正如其他人已经说过的那样,不,您不仅可以使用CSS
,而且js code
可以为您做一点。
Ex.
前任。
jQuery(window).scroll(function(){
var fromTopPx = 200; // distance to trigger
var scrolledFromtop = jQuery(window).scrollTop();
if(scrolledFromtop > fromTopPx){
jQuery('html').addClass('scrolled');
}else{
jQuery('html').removeClass('scrolled');
}
});
And in your CSS file:
在你的 CSS 文件中:
html {
background-repeat: no-repeat;
background-position: center center;
background-attachment: fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
html {
background-image:url(http://robt.info/wp-content/uploads/2013/06/funny-kids-comic-animals.jpg);
}
html.scrolled {
background-image:url(http://robt.info/wp-content/uploads/2013/06/funny-kids-comic-animals_2.jpg);
}
So basically you are adding or removing a class to the HTML tag
at some distance from the top with javascript
(jQuery in this case)... and with CSS
, changing that image.
所以基本上你是HTML tag
在距离顶部一定距离处添加或删除一个类javascript
(在这种情况下是 jQuery)......并使用CSS
,更改该图像。
Now on.. you can apply some transitions to the image, or play with the code to made it slideToggle for example instead changing the class.... and many many other options.
现在.. 你可以对图像应用一些过渡,或者使用代码使其成为例如 slideToggle 而不是改变类......以及许多其他选项。
Good luck
祝你好运
EDIT: Fiddle example: http://jsfiddle.net/pZrCM/
编辑:小提琴示例:http: //jsfiddle.net/pZrCM/