2014-01-29 96 views
0

以下工作正常,但是是否可以訪問'onEnter'內的變量「滾動」值?js訪問變量值

$(document).ready(function() { 

    var $window = $(window); 

    function update() { 

     var scrolled = $window.scrollTop(); 
     return scrolled; 
    }; 



    $('.color').each(function (i, scrolled) { 
     var position = $(this).position(); 

     $(this).scrollspy({ 
      min: position.top, 
      max: position.top + $(this).height(), 
      onEnter: function (element, position, scrolled) { 
       var scrolled = $window.scrollTop(); 
       $window.bind('scroll', update); 
       console.log(scrolled); 
       if (element.id === 'one' || element.id === 'two') { 
        $('.slidingPannel').animate({ 
         'background-position-x': '100%' 
        }, 100); 
       } else { 
        $('.slidingPannel').animate({ 
         'background-position-x': '125%' 
        }, 100); 
       } 
      }, 
      onLeave: function (element, position) { 
       if (console) console.log('leaving ' + element.id); 
      } 
     }); 
    }); 
}); 

回答

1

切換到這一點,你有範圍有關的問題:

$(document).ready(function() { 
var scrolled; 
var $window = $(window); 

function update() { 
    scrolled = $window.scrollTop(); 
}; 



$('.color').each(function (i, scrolled) { 
    var position = $(this).position(); 

    $(this).scrollspy({ 
     min: position.top, 
     max: position.top + $(this).height(), 
     onEnter: function (element, position, scrolling) { 
      scrolled = $window.scrollTop(); 
      $window.bind('scroll', update); 
      console.log(scrolled); // or should this be "scrolling" ? 
      if (element.id === 'one' || element.id === 'two') { 
       $('.slidingPannel').animate({ 
        'background-position-x': '100%' 
       }, 100); 
      } else { 
       $('.slidingPannel').animate({ 
        'background-position-x': '125%' 
       }, 100); 
      } 
     }, 
     onLeave: function (element, position) { 
      if (console) console.log('leaving ' + element.id); 
     } 
    }); 
}); 

});

+0

我得到undefined ..... – Alex

+0

更新的代碼 - 請參閱我在代碼中的評論。 –

+0

嗨,是的,但是我剛剛意識到,通過在'輸入'內放置'滾動',它只會在每次進入新幻燈片時顯示。每當我在'onEnter'中滾動時,我需要訪問'滾動(正如您正確建議的)',因爲我需要爲從右側滑動的面板設置動畫。 – Alex

0

我不認爲你可以將變量名稱作爲參數名稱傳遞給匿名函數。

這是你可以如何處理它。

$(document).ready(function(){ 

var scrolled; 
var $window = $(window); 

function update() { 
    scrolled = $window.scrollTop(); 
}; 



$('.color').each(function (i, scrolledItem) { // edit: changed "scrolled" to "scrolledItem" 
    var position = $(this).position(); 

    $(this).scrollspy({ 
     // some code here 
     onEnter: function (element, position) { 
      // scrolled = $window.scrollTop(); 

      console.log(scrolled); // hopefull should reference scrolled variable as there is no argument with the same name. 

     }, 
     // some code here 
    }); 
}); 

});