我跟着Parallax tutorial on Code.tutsplus,我也看到了其他类似的东西。但是,由于某些原因,没有一个教程能够完美地工作,因为在元素的顶部或底部总是会创建一些空白区域。
所以我决定改变代码,根据元素的高度和视差效果的速度来获取元素的'background-size'属性。但它仍然无法正常工作并在底部创建空白区域。
请检查我的代码,让我知道可能出现的问题:
$('.parallax').each(function(){
var $el = $(this),
speed = $el.data('speed'),
elHeight = $el.outerHeight(),
wHeight = $(window).height(),
elOffset = $el.offset().top;
//Taking into account the amount the background would move and putting that into
//background-size so there are no white spaces.
var extraSize = (elHeight*speed)+elHeight;
var percentage = (extraSize/elHeight)*100;
$el.css({'background-size': percentage+'%'+' '+percentage+'%'});
$(window).scroll(function() {
var diff = $(window).scrollTop() + wHeight - elOffset;
var yPos = -(diff*speed);
var coords = '50% '+ yPos + 'px';
$el.css({ backgroundPosition: coords });
});
});
这里也是css:
.parallax {
background-image: url('http://lorempixel.com/1366/500');
background-position: 50% 0;
background-repeat: no-repeat;
}
请告诉我这里我做错了什么。感谢