2014-01-29 4 views
0

다음은 정상적으로 작동하지만 'onEnter'변수의 'scrolled'값에 액세스 할 수 있습니까?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

정의되지 않음 ..... – Alex

+0

코드가 업데이트되었습니다. 코드의 주석을 참조하십시오. –

+0

안녕하세요. 그렇지만 저는 'onEnter'안에 'scrolled'를 넣으면 새로운 슬라이드에 들어갈 때마다 표시된다는 것을 깨달았습니다. 오른쪽에서 슬라이드하는 패널에 애니메이션을 적용해야하므로 '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 
    }); 
}); 

});