1

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

私が最初にテストしたとき、私は作業バージョンを使用していて、下にスクロールしてもヘッダーが残っているため、2 つの異なる jQuery 関数があります。しかし、ヘッダーヘッダーを固定したままにしておきたいのですが、ユーザーは#contentContainerウィンドウではなくdivをスクロールしているので、に変更すると$(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 に答える