Html 向下滚动页面时移动的背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25369487/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:31:07  来源:igfitidea点击:

background image that moves when you scroll down the page

htmlcss

提问by user3773890

I keep seeing websites with a background image that subtly moves when you scroll down. This is a really nice effect but I'm not sure how to do this? I'm am experienced with html, css and jquery but this is something I haven't done before!

我一直看到带有背景图像的网站,当你向下滚动时,它会巧妙地移动。这是一个非常好的效果,但我不知道如何做到这一点?我对 html、css 和 jquery 很有经验,但这是我以前从未做过的事情!

I have a simple jsfiddle below but I need some help please!

我下面有一个简单的 jsfiddle,但我需要一些帮助!

Many thanks,

非常感谢,

http://jsfiddle.net/def2y2yt/

http://jsfiddle.net/def2y2yt/

Code snippet - more available using the jsfiddle link

代码片段 - 更多使用 jsfiddle 链接

.background {
    background-image: url(example.pjg);
    background-repeat: no-repeat;
    height: 600px;
    width: 100%;
}

回答by Sam

Like TylerH said, it's called Parallax. You can see an example here.

就像 TylerH 说的,它被称为视差。你可以在这里看到一个例子

Using JavaScript:

使用 JavaScript:

var velocity = 0.5;

function update(){ 
var pos = $(window).scrollTop(); 
$('.container').each(function() { 
    var $element = $(this);
    // subtract some from the height b/c of the padding
    var height = $element.height()-18;
    $(this).css('backgroundPosition', '50% ' + Math.round((height - pos) * velocity) +  'px'); 
   }); 
   };

 $(window).bind('scroll', update);

回答by Nathan Peixoto

Or you could use this simple CSS property which I made a blog post about: http://nathanpeixoto.fr/blog/article8/web-un-one-page-presque-sans-javascript(French only, sorry).

或者你可以使用这个简单的 CSS 属性,我写了一篇关于它的博客文章:http: //nathanpeixoto.fr/blog/article8/web-un-one-page-presque-sans-javascript(仅限法语,抱歉)。

Let's say this is your HTML:

假设这是您的 HTML:

<div class="background_container">

</div>
<style>
.background_container{
  background-image: url("XXX");
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed; /* <= This one */
}
</style>

回答by Mohamed El Mahallawy