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

时间:2014-08-18 18:08:44

标签: html css

我一直在看到带有背景图片的网站,当您向下滚动时会巧妙地移动。这是一个非常好的效果,但我不知道该怎么做?我对html,css和jquery有经验,但这是我以前做过的事情!

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

非常感谢,

http://jsfiddle.net/def2y2yt/

代码段 - 使用jsfiddle链接提供更多信息

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

3 个答案:

答案 0 :(得分:17)

像TylerH说的那样,它被称为Parallax。您可以看到示例here.

使用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);

答案 1 :(得分:10)

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

假设这是您的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>

答案 2 :(得分:3)