繁体   English   中英

在调整大小时,将li从嵌套ul移到顶层ul会创建大量lis

[英]On resize, moving li from nested ul into top level ul is creating lots of lis

我正在尝试创建一个响应式菜单。 在移动版本上,我希望ul显示4个列表项。 在调整为桌面大小时,将2个列表项附加到以前未使用的嵌套ul中。 这很好。 但是,如果我将大小调整为移动大小,而不是将2个列表项附加到顶级ul,则似乎会产生很多问题。

 $(document).ready(function() { $('.has-child').click(function() { $(this).toggleClass('clicked'); $('.has-child ul').toggleClass('clicked'); }); }); $(window).on('resize', function() { if ($(window).width() >= 800) { $('.nav-container').detach().appendTo('.header-content'); $('.has-parent').appendTo('.has-child ul'); } else { $('.nav-container').detach().appendTo('.site'); $('.has-parent').appendTo('.site-navigation ul'); } }).trigger('resize'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="nav-container"> <nav class="site-navigation"> <ul> <li><a href="pageone.php">Home</a> </li> <li id="has-child" class="has-child"><a href="#"><i class="ion-person"></i></a> <ul> </ul> </li> <li class="has-parent"><a href="account.php">Account</a> </li> <li class="has-parent"><a href="logout.php">Logout</a> </li> <li><a href="logout.php">Login</a> </li> <li><a href="register.php">Register</a> </li> </ul> </nav> </div> 

提前致谢!

我想我按您的意愿运作了。

但是,我必须说这是一种奇怪的处理方式。 诸如BootstrapFoundation之类的现代框架提供了CSS实用程序类,用于根据所播放的媒体查询来显示和隐藏菜单。

简而言之,您可以拥有2个菜单,然后仅根据css屏幕大小显示或隐藏其中一个菜单。

 $(document).ready(function() { $('.has-child').click(function() { $(this).toggleClass('clicked'); $('.has-child ul').toggleClass('clicked'); }); }); $(window).on('resize', function() { if ($(window).width() >= 800) { $('.nav-container').detach().appendTo('.header-content'); if($('.has-child ul li').length == 0){ $('.header-content .has-parent').detach().appendTo('.has-child ul'); } } else { $('.nav-container').detach().appendTo('.site'); if($('.site-navigation > ul > .has-parent').length == 0){ $('.site .has-parent').detach().appendTo('.site-navigation > ul'); } } }); 
 *{box-sizing: border-box;} .header-content, .site{ float: left; width:50%; background: gray; height: 300px; padding: 30px; } .site{border-left: 2px solid white;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="header-content"> <h4>Header Content</h4> </div> <div class="site"> <h4>Site</h4> </div> <div class="nav-container"> <nav class="site-navigation"> <ul> <li><a href="pageone.php">Home</a> </li> <li id="has-child" class="has-child"><a href="#"><i class="ion-person"></i></a> <ul> </ul> </li> <li class="has-parent"><a href="account.php">Account</a> </li> <li class="has-parent"><a href="logout.php">Logout</a> </li> <li><a href="logout.php">Login</a> </li> <li><a href="register.php">Register</a> </li> </ul> </nav> </div> 

更改大小时,重复大小事件会在您更改浏览器宽度时反复触发。 本质上,要解决此问题,您将需要具有一些指示符,以指示要追加的功能已被触发,并在完成后停止触发。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM