2010-11-18 131 views
1

我不理解JavaScript中的變量。我正在嘗試在localScroll函數出現之前更改/計算「偏移量」(使用變量「theOffset」),或者更優選地調整窗口大小。下面的實例都沒有工作,接受「//初始​​化偏移量」。JavaScript變量不起作用。爲什麼?

如何獲取「$ .localScroll」中的變量「theOffset」進行更改?

jQuery(function($){ 

    //initialize offset 
    var windowWidth = $(window).width(); 
    if (windowWidth < 900) { 
     theOffset = 0; 
    } else { 
     theOffset = ($(window).width() - 900)/-2; 
    } 

$(window).resize(function() { 
    //calculate offset 
    var windowWidth = $(window).width(); 
    if (windowWidth < 900) { 
     theOffset = 0; 
    } else { 
     theOffset = ($(window).width() - 900)/-2; 
    } 
}); 


    $.localScroll({ 
     target: '#content', 
     queue:true, 
     duration:1500, 
     hash:true, 
     stop:true, 
     onBefore:function(e, anchor, $target){ 
      //calculate offset 
      var windowWidth = $(window).width(); 
      if (windowWidth < 900) { 
       theOffset = 0; 
      } else { 
       theOffset = ($(window).width() - 900)/-2; 
      } 
     }, 
     offset: {top:0, left: theOffset, 
     onAfter:function(anchor, settings){ 
      if (windowWidth < 900) { 
       theOffset = 0; 
      } else { 
       theOffset = ($(window).width() - 900)/-2; 
      } 
     } 
    }); 
}); 

如果需要知道,我中心一個div容器在一個奇特的側滾動網站偏移的窗口;)

+0

你在http://www.jslint.com上得到3個錯誤 – 2010-11-18 21:27:55

+0

即使沒有錯誤,同樣的問題仍然存在......'{top:0,left:theOffset}'在執行時被評估,所以沒有任何變量作用域的閉包將會修復這個行爲並且使其不知道/ [ab ]使用scroll-to API /內部或重新調用localScroll函數。 – 2010-11-18 22:53:29

回答

1

你可以宣佈,將通過引用傳遞到offset:您還可以細化幾乎器四功能到一個單一命名功能的myOffset對象:

var myOffset = {top: 0, left: theOffset}; 
function calcOffset() { 
    var windowWidth = $(window).width(); 
    if (windowWidth < 900) { 
    myOffset.left = 0; 
    } else { 
    myOffset.left = (windowWidth - 900)/-2; 
    } 
} 
calcOffset(); 
// note leaving off the() will pass the function as a parameter instead of calling it 
$(window).resize(calcOffset); 

$.localScroll({ 
    target: '#content', 
    queue: true, 
    duration: 1500, 
    hash: true, 
    stop: true, 
    onBefore: calcOffset, 
    offset: myOffset, 
    onAfter: calcOffset 
}); 
0

聲明theOffset jQuery函數

 

var theOffset = 0; 

jquery(function ($) { 
}) 
 
+0

你能解釋爲什麼我能理解嗎? – Dave 2010-11-18 21:30:43

+0

@通過這樣做「theOffset」將獲得全球範圍,並且一次更改它應該在所有其他地方「可見」。 – 2010-11-18 22:42:36

+0

問題是'theOffset'通過的值。 – 2010-11-18 22:45:09

0

我之外認爲你的問題在這裏:

offset: {top:0, left: theOffset, 

首先,你錯過了一個尾部}。其次,你正在做所謂的「按值傳遞」 - 當你調用$ .localscroll()時發送的值實際上是在偏移中指定的值的副本。

您使用的是哪個版本的localScroll?我下載了我能找到的最新源代碼,它的版本是1.2.7,而且我在任何地方都看不到偏移量。

沒有看到localScroll源代碼,我無法想到解決問題的方法。有時候,像這樣的jQuery插件的作者提供了更新選項的方法。如果不是的話,你可能不得不修改localScroll源通過一個回調函數,而不是通過一個對象的屬性來獲取偏移值:

offset: {top:0, left: function() { return theOffset; } } 

注意上面不會沒有修改localScroll源工作通過函數調用而不是選項屬性獲取此數據。

0

注意,在上面的例子,如果你調用setupSomeGlobals()再次創建一個新的閉包(堆棧幀!)。舊的gLogNumber,gIncreaseNumber,gSetNumber變量被具有新閉包的新函數覆蓋。 (在JavaScript中,每當你在另一個函數中聲明一個函數時,每次調用外部函數時都會重新創建函數內部函數)。

相關問題