2012-11-23 75 views
1

我有一点问题,试图检测我的div上的滚动位置。这是我的代码:jQuery来检测滚动的div位置

的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'); 
     } 

    }); 
});