视差滚动在1张图像上工作但在其他图像上没有

我正在努力为我的2张背景图像提供视差效果,它正在处理第一张图片但不在第二张图片上…代码如下

jquery:

$(document).ready(function() { $('section[data-type="background"]').each(function() { var $bgobj = $(this); // assigning the object $(window).scroll(function() { // scroll the background at var speed // the yPos is a negative value because we're scrolling it UP! var yPos = -($window.scrollTop() / $bgobj.data('speed')); // Put together our final background position var coords = '50% '+ yPos + 'px'; // Move the background $bgobj.css({ backgroundPosition: coords }); }); // end window scroll }); }); 

HTML: –

 

Check out this cool parallax scrolling effect. Use these ribbons to display calls to action mid-page.

CSS: –

 .parallax { height:35em; background: url('https://images.unsplash.com/photo-1463123081488-789f998ac9c4?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=6d1a6d1c5a7eb63d0c411b1d019f0b30'); background-repeat: no-repeat; background-position: center center; background-size: cover; } .parallax h2 { color: white; text-align: center; padding: 1em; padding-top: 5em; } .parallax button { display: block; margin: 2em auto; } 

奇怪的是,第二个图像根本没有显示,只有当我删除数据速度属性,然后视差不起作用时才会显示…我感到困惑,所以请协助..

您正在使用$ window.scrollTop(),当您向下滚动页面时,它将变得更大,并将其设置为相对于图像容器的顶部。 好像你需要先从文档顶部减去元素位置:

 $(document).ready(function() { $('section[data-type="background"]').each(function() { var $bgobj = $(this); // assigning the object $(window).scroll(function() { // scroll the background at var speed // the yPos is a negative value because we're scrolling it UP! var yOffset = $bgobj.offset().top; var yPos = -(($window.scrollTop() - yOffset) / $bgobj.data('speed')); // Put together our final background position var coords = '50% '+ yPos + 'px'; // Move the background $bgobj.css({ backgroundPosition: coords }); }); // end window scroll }); }); 

您的第一张图片可能正常工作,因为它位于页面顶部,因此偏移无关紧要?

试试这个

  $(document).ready(function() { $(window).scroll(function() { $('section[data-type="background"]').each(function(i,e) { // scroll the background at var speed // the yPos is a negative value because we're scrolling it UP! var yPos = -($(window).scrollTop() / $(e).data('speed')); // Put together our final background position var coords = '50% '+ yPos + 'px'; // Move the background $(e).css({ backgroundPosition: coords }); }); }); // end window scroll });