2016-01-28 29 views
0

我正在使用下面的代碼爲背景圖像提供一個簡單的視差效果。理想情況下,在CSS中我想要圖像居中(而不是頂部)。但是,只要我開始滾動腳本,它就會跳轉到頂部並開始效果。我無法弄清楚是否有可能改變jQuery,所以它以一個居中的圖像開始?誰能幫忙?背景中心視差效果跳轉到頂部

<div id="para" style="background-image: url('blah')" data-speed="8" data-type="background"> 
</div> 

#para { 
    height:500px; 
    float:left; 
    width:100%; 
    background-size:100%; 
    background-position: center center; 
    background-repeat: no-repeat; 
    background-attachemnt: fixed; 
} 

//Parallax 
$(document).ready(function() { 
    if ($(window).width() > 1025) { 
     // Cache the Window object 
     $window = $(window); 
     $('div[data-type="background"]').each(function() { 
      var $bgobj = $(this); 
      $(window).scroll(function() { 
       var yPos = -($window.scrollTop()/$bgobj.data('speed')); 
       var coords = '50% ' + yPos + 'px'; 
       $bgobj.css({ 
        backgroundPosition: coords 
       }); 
      }); 
     }); 
    } 
}); 

回答

1

你不能給背景位置一個百分比和像素。它應該是一個或另一個。使用百分比單位,然後將您的$ window.scrollTop()也設置爲百分比。所以乘以100,然後除以$ window.height()。

//Parallax 
$(document).ready(function() { 

    if ($(window).width() > 1025) { 
     // Cache the Window object 
     $window = $(window); 
     $('div[data-type="background"]').each(function() { 
      var $bgobj = $(this); 
      $(window).scroll(function() { 
       var yPos = 50 - ($window.scrollTop() * 100/$window.height()/$bgobj.data('speed')); 
       var coords = '50% ' + yPos + "%"; 
       $bgobj.css({ 
        backgroundPosition: coords 
       }); 
      }); 
     }); 
    } 
}); 

您的數據速度屬性也需要降低。我發現0.5工作得很好。

<div id="para" style="background-image: url('blah')" data-speed="0.5" data-type="background"> 

+0

這是完美的,謝謝!我一直在努力讓自己的頭腦對數學有所瞭解,但這不僅非常合理。有用! –

+0

沒問題。我很高興能幫上忙! – Th4n0s