简体   繁体   中英

How i can improve this code (fixed navbar)?

I made this for i can fix navbar on site when i scroll page

How i can improve this code, can reduce it somehow?

<nav class="main_menu">
// some code...
</nav>

var menu_offset_top_default = $('.main_menu').offset().top;
$(window).scroll(function() {
    var menu_offset_top = $('.main_menu').offset().top;
    if ($(window).scrollTop() >= menu_offset_top) {
        $('.main_menu').addClass('fixed-top');
    }
    if ($(window).scrollTop() < menu_offset_top_default || $(window).scrollTop() <= 0) {
        $('.main_menu').removeClass('fixed-top');
    }
});

You could use css position: sticky instead and get remove the jquery code

A stickily positioned element is an element whose computed position value is sticky. It's treated as relatively positioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the container it scrolls within), at which point it is treated as "stuck" until meeting the opposite edge of its containing block. Source .

An example:

https://codepen.io/simevidas/pen/JbdJRZ

You can just do it as follows with simple if-else block.

$(window).scroll(function() {
    if ($(window).scrollTop() >= $('.main_menu').offset().top) {
        $('.main_menu').addClass('fixed-top');
    }
    else {
        $('.main_menu').removeClass('fixed-top');
    }
});

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