【问题标题】:jQuery to Detect Scrolling Div PositionjQuery 检测滚动 div 位置
【发布时间】:2012-11-23 04:10:31
【问题描述】:

我在尝试检测 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).

谢谢。

【问题讨论】:

  • 你想要this
  • this ?最后一个和你的一样
  • 他们都工作得很好。谢谢。
  • @eicto 您应该将其中一个作为答案或两者兼而有之。

标签: jquery html css blackberry blackberry-webworks


【解决方案1】:

也许你可以用这个?

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

    });
});

【讨论】:

    猜你喜欢
    • 2013-09-26
    • 2014-02-08
    • 2012-12-07
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多