如何使用 CSS 更改滚动背景? [英] How do I change my background on scroll using CSS?

查看:38
本文介绍了如何使用 CSS 更改滚动背景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站有完美的全页背景图片.我从 css 技巧 中获取了它的代码.

My website has THE PERFECT FULL PAGE BACKGROUND IMAGE. I grabbed the code for it from css tricks.

如果您访问我的网站,您可以看到它的实际效果:<网站不再可用>

If you visit my site you can see it in action: <site no longer available>

我想知道的是,有没有一种方法可以让我在滚动一定长度后将此图像更改为不同的图像?

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?

我的目标是拥有相同的图像,但从狗嘴里冒出一个气泡,我猜有 2 个图像可以做到这一点.

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.

这只能在 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;
}

推荐答案

正如其他人已经说过的,不,你不仅可以使用 CSS,还可以使用一点 js 代码 可以为你做.

As others already said, Nop, you can't only with CSS, but a little js code can do it for you.

例如

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');
    }
});

在你的 CSS 文件中:

And in your CSS file:

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);
}

所以基本上你是用 javascript(在这种情况下是 jQuery)在离顶部一定距离的 HTML 标签 中添加或删除一个类......code>CSS,更改图像.

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.

现在......你可以对图像应用一些过渡,或者使用代码使其成为例如 slideToggle 而不是改变类......以及许多其他选项.

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.

祝你好运

小提琴示例:http://jsfiddle.net/pZrCM/

这篇关于如何使用 CSS 更改滚动背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆