Navbar resizing based on screen size

时间:2018-03-22 23:30:24

标签: jquery html css

I am trying to make my navbar (and logo) shrink when scrolling down on larger screens where the mobile menu button is not visible (> 768px), and have it remain at a fixed smaller size on smaller screens.

Standard Bootstrap 3 classes for the HTML, the javascript I have right now that doesn't seem to be working the way I want is below. It is applying the nav resizing that I want but on all screen sizes. I want it to only apply the changes on the larger screens.

function resize() {
if ($(window).width() > 768) {
$(window).scroll(function() {
    if ($(".navbar").offset().top > 50) {
        $(".navbar-fixed-top").addClass("shrink-nav");
      $(".navbar-brand img").addClass("shrink-logo");
    } else {
        $(".navbar-fixed-top").removeClass("shrink-nav");
      $(".navbar-brand img").removeClass("shrink-logo");
    }
});
} else {
$(".navbar-fixed-top").addClass("shrink-nav");
$(".navbar-brand img").addClass("shrink-logo");
}
}

resize();

The CSS I am using for the modifier classes is below.

.shrink-logo {
position: relative;
height: 60px;
top:15px;
  }

.shrink-nav {
 height:70px;
 padding: 15px 0;
 }

Any help is appreciated!

2 个答案:

答案 0 :(得分:0)

try this

resize();
$(window).resize(resize);
$(window).scroll(resize);

function resize() {
    if ($(window).width() > 768) {
         if ($(".navbar").offset().top > 50) {
             $(".navbar-fixed-top").addClass("shrink-nav");
             $(".navbar-brand img").addClass("shrink-logo");
         } else {
            $(".navbar-fixed-top").removeClass("shrink-nav");
            $(".navbar-brand img").removeClass("shrink-logo");
         }
     } else {
         $(".navbar-fixed-top").addClass("shrink-nav");
         $(".navbar-brand img").addClass("shrink-logo");
     }
 }

答案 1 :(得分:0)

试试这段代码片段。我想这会对你有帮助......

resize();
$( window ).resize(resize);
function resize() {
    if ($(window).width() > 768) {
         if ($(".navbar").offset().top > 50) {
             $(".navbar-fixed-top").addClass("shrink-nav");
             $(".navbar-brand img").addClass("shrink-logo");
         } else {
            $(".navbar-fixed-top").removeClass("shrink-nav");
            $(".navbar-brand img").removeClass("shrink-logo");
         }
     } else {
         $(".navbar-fixed-top").addClass("shrink-nav");
         $(".navbar-brand img").addClass("shrink-logo");
     }
 }