2012-11-23 5 views
1

내 div에서 스크롤 위치를 검색하려고 문제가 조금 있습니다. 이건 내 코드입니다 :스크롤 div 위치를 jQuery 검색

index.html을

<div id="wrapper"> 
    <div id="headerOne">I am a header</div> 
    <div id="contentContainer"> 
    <div id="content"> 
     I am some content 
    </div> 
    </div> 
</div> 

jQuery를 기능 (작동하지 않는 버전)

$(document).ready(function() { 

    var aboveHeight = $('#headerOne').outerHeight(); 

$('#contentContainer').scroll(function(){ 
     if ($('#contentContainer').scrollTop() > aboveHeight){ 
     $('#headerOne').addClass('fixed').css('top','0').next().css('padding-top','60px'); 
     } else { 
     $('#headerOne').removeClass('fixed').next().css('padding-top','0'); 
    } 
    }); 
    }); 

jQuery를 기능 (작업 버전)

$(document).ready(function() { 

    var aboveHeight = $('#headerOne').outerHeight(); 

$(window).scroll(function(){ 
     if ($(window).scrollTop() > aboveHeight){ 
     $('#headerOne').addClass('fixed').css('top','0').next().css('padding-top','60px'); 
     } else { 
     $('#headerOne').removeClass('fixed').next().css('padding-top','0'); 
    } 
    }); 
    }); 

두 가지 jQuery 기능이 있습니다. 처음 테스트했을 때 작업 버전 을 사용 중이었고 스크롤 할 때 헤더가 그대로 남아 있었기 때문입니다. 하지만 머리글 머리글을 고정 된 상태로 유지하려면 #contentContainer div가 스크롤되지 않으므로 $(window).에서 $('#contentContainer')으로 변경하고 더 이상 작동하지 않습니다.

스크롤 기능이 div 스크롤을 감지 할 수 있습니까? 아니면 $(window).이어야합니까?

감사합니다.

+0

[this] (http://jsfiddle.net/oceog/jsCh8/)? –

+0

또는 [this] (http://jsfiddle.net/oceog/jsCh8/3/)? 마지막 하나는 –

+0

과 동일합니다. 둘 다 훌륭하게 작동합니다. 고맙습니다. – Jamie

답변

0

아마도 이것을 사용할 수 있습니까?

jQuery(document).ready(function($) { 
    //Calculate the height of <header> 
    //Use outerHeight() instead of height() if have padding 
    var aboveHeight = 130; 

    //when scroll 
    $(window).scroll(function(){ 

     //if scrolled down more than the header’s height 
     if ($(window).scrollTop() > aboveHeight){ 

      // if yes, add “fixed” class to the <nav> 
      // add padding top to the #content 
      //(value is same as the height of the nav) 
      $('nav').addClass('fixed').css('top','0').next() 
      .css('padding-top','60px'); 

     } else { 

      // when scroll up or less than aboveHeight, 
      //remove the “fixed” class, and the padding-top 
      $('nav').removeClass('fixed').next() 
      .css('padding-top','0'); 
     } 

    }); 
}); 
관련 문제