简体   繁体   English

具有嵌套链接的CSS / JavaScript / HTML菜单列表

[英]CSS/JavaScript/HTML Menu list with nested links

I have menu list in my page with following structure. 我的页面上具有以下结构的菜单列表。 When I click any link in the menu the system automatically add class="is-active" to the link. 当我单击菜单中的任何链接时,系统会自动将class =“ is-active”添加到该链接。 I set display of nested links to none so they will be visible only by clicking on parent link (see css). 我将嵌套链接的显示设置为无,因此只有通过单击父链接才能看到它们(请参阅css)。 However, when I click on one of the child links, the whole submenu of child links disappear. 但是,当我单击子链接之一时,子链接的整个子菜单都会消失。 How to achieve that my child links will be visible when I use them? 使用我的子链接时如何实现可见? I know I cannot affect parent by child with css, maybe there is some simple javascript workaround. 我知道我无法通过CSS影响孩子的父母,也许有一些简单的javascript解决方法。

Thank you in advance! 先感谢您!

 .menu-item--expanded ul {display: none;} .menu-item--expanded a.is-active ~ ul {display: block} 
 <html> <body> <ul> <li class="menu-item--expanded"> <a class="is-active">Link 1</a> <ul> <li><a href="">Link A</a></li> <li><a href="">Link B</a></li> <li><a href="">Link C</a></li> </ul> </li> <li class="menu-item--expanded"> <a>Link 2</a> <ul> <li><a href="" class="is-active">Link D</a></li> <li><a href="">Link E</a></li> <li><a href="">Link F</a></li> </ul> </li> </ul> </body> </html> 

I would do something like this on javascript: 我会在javascript上执行以下操作:

$('li').on('click', function(evt){
    $(evt.target).parent().css('display', 'none');
})

so when a list item is clicked then set as display:none the parent element, so ul. 因此,当单击列表项时,将其设置为display:none父元素,所以ul。 Maybe have a check around the setting of css to check is-active class too, like: 也许也可以检查css的设置来检查is-active类,例如:

if($(evt.target).hasClass('is-active')){
 //switch to display none
}

i would suggest using jquery for this. 我建议为此使用jQuery。 The following code will change the display from the child ul when clicked on a parent. 以下代码将在单击父对象时更改子ul的显示。

make sure that the child lists are display: none with css. 确保显示子列表:没有带CSS的子列表。

.menu-item--expanded > ul{
display: none;
}

$('.menu-item--expanded').click(function () {
  $(this).find($('ul')).css({
    'display' : 'block'
  });
});

to make sure that only the childs of the parent page where you are are visible use the following code: 为确保只有可见的父页面的子代使用以下代码:

note: the else clause is not needed actually since your css will already set display none on those items. 注意:实际上不需要else子句,因为您的CSS已经设置了在这些项目上不显示任何内容。 but i mentioned it just to make it clear. 但我只是为了清楚起见提到了它。

$('.menu-item--expanded').each(function () {
  if($(this).find($('>a')).hasClass('is-active')){
    $(this).find($('ul')).css({
      'display' : 'block'
    });
  } else {
    $(this).find($('ul')).css({
      'display' : 'none'
    });
  }
});

hope this helps. 希望这可以帮助。

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

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