一个迟到的答案,但我想到了这个,不知何故我为这个做了一个破解。
这个想法是创建一个内部元素,它将保存背景图像并充当background-attachment:fixed
属性。
由于这个属性使背景图像的位置相对于窗口,我们必须在它的容器内移动内部元素,这样我们就会得到这种效果。
var parallax_container = $(".parallax_container");
/*Create the background image holder*/
parallax_container.prepend("<div class='px_bg_holder'></div>");
$(".px_bg_holder").css({
"background-image" : parallax_container.css("background-image"), /*Get the background image from parent*/
"background-position" : "center center",
"background-repeat" : "no-repeat",
"background-size" : "cover",
"position" : "absolute",
"height" : $(window).height(), /*Make the element size same as window*/
"width" : $(window).width()
});
/*We will remove the background at all*/
parallax_container.css("background","none");
parallax_container.css("overflow","hidden");/*Don't display the inner element out of it's parent*/
$(window).scroll(function(){
var bg_pos = $(window).scrollTop() - $(".parallax_container").offset().top; /*Calculate the scrollTop of the inner element*/
$(".px_bg_holder").css({
"margin-top" : bg_pos+"px"
});
});
$(window).resize(function(){
$(".px_bg_holder").css({
"height" : $(window).height(),
"width" : $(window).width()
});
});