Bootstrap 3导航栏按屏幕尺寸适配滚动收缩问题
Got it, let's sort out this navigation bar behavior for your Bootstrap 3 project. The core issue here is that your current JS applies the shrink effect to all screen sizes—we just need to add a viewport width check to limit it to desktop layouts (where the mobile menu button is hidden, i.e., screens larger than 768px). Here's how to adjust things:
Updated JavaScript Code
function handleNavbarShrink() { // Only apply scroll-based shrink to screens wider than 768px if ($(window).width() > 768) { // Trigger shrink when user scrolls past a threshold (adjust 50 to your preference) if ($(document).scrollTop() > 50) { $('.navbar').addClass('navbar-shrink'); $('.navbar-brand img').addClass('logo-shrink'); // Include this if you need to resize your logo too } else { $('.navbar').removeClass('navbar-shrink'); $('.navbar-brand img').removeClass('logo-shrink'); } } else { // For mobile screens (<=768px), force the navbar to stay in its small fixed state $('.navbar').addClass('navbar-shrink'); $('.navbar-brand img').addClass('logo-shrink'); // If you'd rather keep the default mobile navbar style instead, swap to removeClass here: // $('.navbar').removeClass('navbar-shrink'); // $('.navbar-brand img').removeClass('logo-shrink'); } } // Initialize on page load, and attach to scroll/resize events $(document).ready(function() { handleNavbarShrink(); $(window).on('scroll resize', function() { handleNavbarShrink(); }); });
Critical Details to Note:
- Viewport Breakpoint: Bootstrap 3 uses
768pxas the line between mobile and desktop layouts, so our$(window).width() > 768condition ensures the scroll effect only runs where the mobile menu is hidden. - Mobile Lock: The
elseblock explicitly sets the navbar to your desired small state on mobile, keeping it fixed regardless of scrolling (adjust toremoveClassif you prefer the default mobile navbar style instead). - CSS Pairing: Make sure you have corresponding CSS for the shrink classes to define the smaller styles. Example:
/* Base navbar styles */ .navbar { transition: all 0.3s ease; padding: 15px 0; } /* Shrunken navbar style */ .navbar-shrink { padding: 5px 0; background-color: #ffffff; /* Adjust to your navbar's desired color */ } /* Base logo styles */ .navbar-brand img { height: 50px; transition: height 0.3s ease; } /* Shrunken logo style */ .navbar-shrink .navbar-brand img { height: 30px; }
Why This Works:
- We centralized all navbar logic into one reusable function that runs on page load, scroll, and resize events—so it adapts instantly if the user resizes their browser window.
- The width check prevents the scroll effect from messing with your mobile navbar, keeping it locked to the fixed small size you requested.
内容的提问来源于stack exchange,提问作者Brian Williams
相关产品推荐
相关产品推荐

