1

我在尝试检测 div 上的滚动位置时遇到了一些问题。这是我的代码:

索引.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 函数,因为当我第一次测试时,我使用的是工作版本,并且向下滚动时标题保持不变。但我希望标题标题保持固定用户正在滚动#contentContainerdiv 而不是窗口,所以我将其更改$(window).$('#contentContainer')并且它不再工作了。

滚动功能可以检测 div 滚动还是必须检测$(window).

谢谢你。

4

1 回答 1

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

    });
});
于 2012-11-23T11:19:40.730 回答