2014-04-22 6 views
0

我想使此功能僅在屏幕尺寸高於1024像素時才起作用。使功能在特定的寬度上工作

//Parallax background image 
    var velocity = 0.5; 
    function update(){ 
     var pos = $(window).scrollTop(); 
     $('.parallax').each(function() { 
      var $element = $(this); 
      var height = $element.height(); 
      $(this).css('background-position', '40%' + Math.round((height - pos) * velocity) + 'px'); 
     }); 
    };$(window).bind('scroll', update); update(); 

這是我試圖做:

//Parallax background image 
    var velocity = 0.5; 
    $(window).on("ready resize", function() { 
    if ($(window).width() < 770) { 

    function update(){ 
     var pos = $(window).scrollTop(); 
     $('.parallax').each(function() { 
      var $element = $(this); 
      var height = $element.height(); 
      $(this).css('background-position', '40%' + Math.round((height - pos) * velocity) + 'px'); 
     }); 
    };});$(window).bind('scroll', update); update(); 

我真的不知道我在做什麼錯?

+0

根據您的要求,您的條件應該是'if($(window).width()> 1024){' –

+0

呵呵,現在改變這個 – Leo

+0

仍然沒有做任何事 – Leo

回答

1

您沒有說明什麼問題你重新來過是。如果它是「我的代碼不起作用」,那麼也許你應該首先檢查你的語法。你的大括號搞砸了。

//Initialize velocity and empty update function 
var velocity = 0.5; 
var update = function() {}; 

//When window is ready (content loaded) OR resized, execute the following function 
$(window).on("ready resize", function() { 
    if ($(window).width() >= 1024) { //Check if window width is 1024px wide or larger 
     update = function() { //Set update to run this function when executed. 
      var pos = $(window).scrollTop(); //Get scrollbar position https://api.jquery.com/scrollTop/ 

      //For each element with 'parallax' class, execute the following function 
      $('.parallax').each(function() { 
       var $element = $(this); //Get the current parallax-classed element 
       var height = $element.height(); //Save the current height of this element 

       //Set the CSS of this parallax-classed element set the background position 
       $(this).css('background-position', '40% + ' + Math.round((height - pos) * velocity) + 'px'); 
      }); 
     }; 
    } else { //Execute if screen width is < 1024px 
     update = function() {}; //Set update to do nothing 
    } 
}); 

//When window is scrolled through, run the update function 
$(window).bind('scroll', update); 
//update(); 

最後一行是不必要的,因爲resize將處理函數值,並且scroll將處理的執行。

您在background-position設置中丟失了+-

因此,例如,如果您的Math.round()的結果是「30」,那麼Javascript會將該行解釋爲$(this).css('background-position', '40%30px');,這顯然會導致問題。我相信你想要它說一些像$(this).css('background-position', '40% + 30px');

+0

這不適用於我的隊友 – Leo

+0

哪部分不工作?你需要更具體。調試的常用方法是在代碼的關鍵點插入'console.log'語句,以查看您的語句是否得到正確執行。如果你沒有看到這些消息,那麼你的問題在代碼中更高。 http://stackoverflow.com/questions/4539253/what-is-console-log –

+0

什麼都沒有顯示出來,我已經試過了,當我用這個替換舊代碼時,函數停止工作 – Leo

相關問題