简体   繁体   中英

How could i detect breakpoints of a header with variable number of menus?

I'm creating a header for a web application and i want this header to be configurable : admin can add or remove menus as he want. For example : 在此处输入图片说明 Or 在此处输入图片说明

The breakpoint of these two navbar isn't the same. So I'm wondering how could i deal with that ? How can I detect that the menus are too long for the screen so i have to reduce it ?

Media queries are fixed so it's not a good solution and I don't find how to do that in JavaScript.

Here is a basic approach. It uses jQuery to detect the distance between the logo and the menu items, and if it goes below an arbitrary value (100px here), some css is added. You could expand this to do whatever you'd like when the distance gets too small. Lower the padding, logo size, swap in a mobile menu, etc.

jsfiddle here

 $(window).on('load resize', function() { var menuOffset = $('.menu-items').offset().left var logoWidth = $('.logo').width(); if (menuOffset - logoWidth <= 100) { $('.menu-items').css('background-color', 'red'); } else if (menuOffset - logoWidth > 100) { $('.menu-items').css('background-color', 'blue'); } }); 
 body { font-family: helvetica; font-weight: bold; } .nav { display: flex; flex-direction: row; justify-content: space-between; align-items: center; } .nav .menu-items { display: flex; } .nav .menu-items .item { padding: 0 10px; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <nav class="nav"> <div class="logo"> logo </div> <div class="menu-items"> <div class="item"> item </div> <div class="item"> item </div> <div class="item"> item </div> <div class="item"> item </div> <div class="item"> item </div> <div class="item"> item </div> <div class="item"> item </div> </div> </nav> 

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