简体   繁体   中英

ScrollTop not reverting back when scroll to top

Having problems with Scrolltop - have got it to change smoothly when scrolling down, but doesn't revert to the original css when scrolling back up.

I've tried switching the order around but nothing works. Can anyone tell me where my code is wrong?

Thanks

$(function() {
    var topblock = $(".topblockfix");
    var header = $(".header");
    $(window).scroll(function() {   
        var scroll = $(window).scrollTop();
        if ($(window).scrollTop() > $('.topblockfix').offset().top) {
        if (scroll >= 250) {
            topblock.removeClass("topblockfix").addClass("topblockfix-alt");
            header.removeClass("header").addClass("header-alt");
        } else {
            topblock.removeClass("topblockfix-alt").addClass("topblockfix");
            header.removeClass("header-alt").addClass("header");
        }
        }
    });
});

You have a logical mistake in the first if-statement.

You are checking the offset top of $('.topblockfix'). But you remove the class .topblockfix and set it to .topblockfix-alt.

So you need to update your if statement:

if ($(window).scrollTop() > $('.topblockfix').offset().top || $(window).scrollTop() > $('.topblockfix-alt').offset().top) {

or you have to cache the value of $('.topblockfix').offset().top somewhere

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