简体   繁体   中英

Div stops at the top when scrolling

I am trying to make a div change class to fixed when it reach the top of the page.

I have this JavaScript code.

<script type="text/javascript">
    $(function () {

        var top = 200;
        var y = $(this).scrollTop();

        if (y >= top) {
            // if so, add the fixed class
            $('#kolonne-v').addClass('fixed');
        } else {
            // otherwise remove it
            $('#kolonne-v').removeClass('fixed');
        }
    });
</script>

What am i doing wrong?

Demo jsFiddle

JS

$(function () {
    var top = 200; 
    //this should be the offset of the top of your div 
    //which can be found by doing the following line

    //var top = $("#kolonne-v").offset().top;

    $(window).on('scroll', function () {
        if (top <= $(window).scrollTop()) {
            // if so, add the fixed class
            $('#kolonne-v').addClass('fixed');
        } else {
            // otherwise remove it
            $('#kolonne-v').removeClass('fixed');
        }
    })
});

Description

This uses the jquery .on('scroll', handler) method, documentation here . The basic principal is that on document.ready you set the scroll point when your div becomes fixed to the top. Then you setup an .on('scroll', handler) event that triggers whenever the window is scrolled in. If the user scrolls to your point you add the fixed CSS class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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