使用jQuery更新滚动时的多个背景位置?

时间:2014-09-20 10:48:48

标签: javascript jquery css

视差脚本不会更新$(window).scroll上的css。看起来你不能用jQuery添加多个背景位置?

视差滚动脚本:

<script>
var top_header = '';
$(document).ready(function(){
  top_header = $('header');
});
$(window).scroll(function () {
  var st = $(window).scrollTop();
  top_header.css({'background-position':"left "+(st*.5)+"px,"});
});
</script>

CSS:

header {background-image: url(../images/1.png), url(../images/2.png);
        background-repeat: no-repeat, no-repeat;
        background-position: left, right; 
        height: 550px; width: 100%}

我试图像这样更新css:

$(window).scroll(function () {
  var st = $(window).scrollTop();
  top_header.css({'background-position':"left "+(st*.5)+"px,"+","+"right "+(st*.5)+"px,"});
});

这会对代码进行制动,并且标题的背景位置不会在滚动时更新。

任何想法都赞赏。

Working example
Not working example

2 个答案:

答案 0 :(得分:1)

在css中,您设置multiple background这样的位置:

 background-position: bottom right, left, right;

这意味着你的代码应该看起来像这样

$(window).scroll(function () {
  var st = $(window).scrollTop();
  top_header.css({'background-position':"left "+(st*.5)+"px," + "right "+(st*.5)+"px;"});
});

答案 1 :(得分:0)

对于多个背景图像,您应该使用以下结构:

background-image:url(1), url(2), ...;
background-repeat: no-repeat(1), no-repeat(2) , ...;
background-size: 50% 50% (1),50% 50%(2) ,...;
background-position: left center(1), right center(2), ....;

OR

background: 
   url(1) 600px 10px no-repeat,  /* On top,    like z-index: 4; */
   url(2) 10px 10px no-repeat,   /*            like z-index: 3; */
   url(3); 

使用JQuery

var top_header = '';
$(document).ready(function () {
    top_header = $('header');
});
$(window).scroll(function () {
    var st = $(window).scrollTop();
    top_header.css({
        'background-position': "left center," + "right " + (st * .5) + "px"
    });
});
$("#btnAdd").click(function () {
    var bg = $("header").css('background-image');
    $("header").css('background-image', bg + ', url("http://www.wired.com/wp-content/uploads/images_blogs/rawfile/2013/11/offset_RonnyRitschel_23712-1-660x660.jpg")');
});

在演示中,首先单击Add bg并滚动页面以查看结果

DEMO