简体   繁体   English

在div中滚动时使用jQuery添加/删除类

[英]Adding/removing a class with jQuery when scrolling inside a div

I have a child <div> which has position: fixed; 我有一个孩子<div> ,其position: fixed; applied by adding a class of is-active when you scroll past the top of it's parent <div> . 通过滚动到其父类<div>的顶部时添加is-active类来应用。

Is it possible to fix the position of the child at the end of the parent as you scroll beyond the end of the parent? 滚动到父级末尾时,是否可以将子级的位置固定在父级末尾? And then re-apply the class 'is-active' to the child when you scroll back up above the end of the parent? 然后,当您向上滚动到父级末尾时,将“活动”类重新应用于子级吗?

Essentially I'd like the fixed position of the child to only be active within it's parent. 本质上,我希望孩子的固定位置仅在其父对象中处于活动状态。 I want to achieve what position: sticky; 我想达到什么position: sticky; can do without the polyfill overhead and lack of browser support. 可以在没有polyfill开销和缺乏浏览器支持的情况下完成。 Is this possible? 这可能吗?

Here's what I have currently: 这是我目前所拥有的:

HTML: HTML:

<div class="outer">
    <div class="nav">
    </div>
</div>
<div class="end">
</div>

CSS: CSS:

.outer {
    position: relative;
    width: 100%;
    height: 200rem;
    margin: 10rem 0 0;
    background: red;
}

.end {
    width: 100%;
    height: 40rem;
    background: green;
}

.nav {
    position: absolute;
    top: 0;
    left: 0;
    width: 10rem;
    height: 30rem;
    background: blue;

    &.is-active {
        position: fixed;
        top: 2rem;
        left: 2rem;
    }

}

jQuery: jQuery的:

var $nav = $('.nav');
var $outer = $('.outer');

$(function(){
  $(window).scroll(function() {
    var $scroll = $(window).scrollTop();
    var $parentOffset = $outer.offset().top;
    var $parentHeight = $outer.height();
    var $navHeight = $nav.height();
    if($scroll > $parentOffset && $scroll < ($parentHeight - $navHeight)) {
      $nav.addClass('is-active');
    }
    else {
      $nav.removeClass('is-active');
    });
});

Here's Codepen with a working example also: https://codepen.io/abbasarezoo/pen/BwXBLv 这是Codepen的工作示例: https ://codepen.io/abbasarezoo/pen/BwXBLv

Thanks for any help in advance! 感谢您的任何帮助!

i just changed it now sticky header is working https://codepen.io/anon/pen/OxKPbj 我刚刚更改了它,现在粘性标头正在工作https://codepen.io/anon/pen/OxKPbj

if($scroll > $parentOffset && $scroll ) {
                    $nav.addClass('is-active');
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM