【问题标题】:Add a class to a DIV when top of the window reach a specific element and remove it when not当窗口顶部到达特定元素时将类添加到 DIV 并在未到达时将其删除
【发布时间】:2013-12-01 15:56:52
【问题描述】:

我在包装的顶部有一个.navigation。 我想添加一个.fixed 类,当窗口顶部到达.bottom DIV 并在.bottom 的顶部在窗口范围内时删除这个类(这是添加和删除之间的切换.固定类)。

<div id="wrapper">
    <div class="navigation">
        <!-- There are some list elements here -->
    </div>
    <div class="bottom"></div>
</div>

这是我做的,但是不行

bottom     = $('.bottom');
$(window).scroll(function(){    
    if ($(this).scrollTop() > bottom){ 
        $('.navigation').addClass('fixed'); 
    }
    else{
        $('.navigation').removeClass('fixed');
    }
});

【问题讨论】:

  • 可视化你的需求很好,但是你的代码在哪里?
  • .navigation 是如何滚动的?
  • @acdcjunior 使用默认浏览器滚动条滚动

标签: javascript jquery html css


【解决方案1】:

var bottom = $('.bottom').offset().top;

应该可以的。

这会将视口顶部的偏移量与窗口的scrollTop() 进行比较,而不是比较整个元素。

【讨论】:

  • 很高兴我能帮上忙。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-08
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多