jquery手风琴_有史以来最简单的jQuery手风琴

jquery手风琴

Sometime ago someone asked in this Experts-Exchange question how to build an Accordion menu . Well, Accordion menus are really fascinating: they take up little space in our page even if they hold tenths of menu items and this way Accordion menus allow us to build very large menus without breaking our layout. And that animation! Don't you find it amazing?

某个时候,有人在此Experts-Exchange中询问如何构建手风琴菜单。 好吧,手风琴菜单真的很有趣:即使它们容纳十分之一的菜单项,它们在我们的页面中也只占很小的空间,通过这种方式,手风琴菜单使我们能够在不破坏布局的情况下构建非常大的菜单。 还有那个动画! 你不觉得很棒吗?

For those who ignore what an accordion menu is, let me use Wikipedia words:

对于那些忽略什么是手风琴菜单的人,让我用维基百科的单词:

The graphical control element accordion is a vertically stacked list of items, such as labels or thumbnails. Each item can be "expanded" or "stretched" to reveal the content associated with that item. There can be zero expanded items, exactly one, or more than one items expanded at a time, depending on the configuration.

图形控制元素 手风琴是垂直堆叠的项目列表,例如标签或缩略图 。 可以“扩展”或“拉伸”每个项目以显示与该项目关联的内容。 取决于配置,展开的项目可以为零,一次可以恰好一个,也可以不止一个。

The term stems from the musical accordion in which sections of the bellows can be expanded by pulling outward.

该术语源自音乐手风琴 ,其中波纹管的各个部分可通过向外拉动来扩展。

Maybe some images can clarify the concept:

也许有些图片可以澄清这个概念:

accordion.jpg

As you can see, in the first image the menu is closed; when you click, let's say, 'First courses' item, its submenu is shown. But when you click another item, 'Steak' for instance, this one is shown whereas the first one is gracefully hidden.

如您所见,在第一个图像中,菜单已关闭; 单击时,假设“ 第一门课程 ”项显示其子菜单。 但是,当您单击另一个项目(例如“ 牛排 ”)时,将显示该项目,而第一个项目则被优雅地隐藏。

To witness the success of this technique is simply the extraordinary number of plugins that you can find on the net: just go to Google and type 'Accordion plugin' and you'll navigate in an ocean of different options.

要见证此技术的成功,您可以在网上找到大量的插件:只需转到Google并输入“ Accordion插件”,您便会浏览各种各样的选项。

But I want to show you is that you don't need any plugin to build a fully functional, infinitely extensible Accordion menu: just 11 lines of jQuery (parenthesis included)!

但我想向您展示的是,您不需要任何插件即可构建功能齐全,可无限扩展的手风琴菜单:只需11行jQuery(包括括号)!

有史以来最简单的手风琴菜单! (The simplest accordion menu ever!)

Let's start with our Accordion. It will have a couple of great features:

让我们从手风琴开始。 它将具有两个重要功能:

  1. it can be extended as we need without modifying the underlying jQuery code: we can add an infinite number of submenus and items just using a couple of css classes;

    它可以根据需要进行扩展,而无需修改底层的jQuery代码:只需使用几个CSS类就可以添加无限数量的子菜单和项目;
  2. every time we'll click on a menu item to show its children we want automatically close any other open menu regardless its level (except of course the one we are in).

    每次我们单击菜单项以显示其子级时,我们都希望自动关闭任何其他打开的菜单,无论其级别如何(当然,我们所在的菜单除外)。

基本标记 (The basic markup)

So, look at the following markup for our menu. We'll use the element nav to wrap the series of unordered lists that will build menus and submenus. We give to the main list the id "mg-accordion" (you know, mg stays for Marco Gasi ;) ) Then we'll use class "dropdown" to mark all li elements which hold a submenu and the class "submenu" to mark the ul element which represent the submenu hold by the dropdown list item. In the following snippet you can see highlighted all the lines where these classes are used:

因此,请查看以下菜单标记。 我们将使用元素nav来包装将构建菜单和子菜单的一系列无序列表。 我们在主列表中输入id“ mg-accordion ”(您知道, mg代表Marco Gasi;))然后,我们将使用“ dropdown ”类标记所有包含一个子菜单的li元素,并将“ submenu ”类用下拉列表项标记代表子菜单的ul元素。 在以下代码片段中,您可以看到突出显示了使用这些类的所有行:

<nav>
    <ul id="mg-accordion" role="navigation" class="row">
        <li><a href="#" title="">All Italian Recipes</a></li>
        <li class="dropdown"><a href="#" title="">First courses</a>  
            <ul class="submenu">
                <li><a href="#">All first courses</a></li>    
                <li><a href="#">All pasta's recipes</a></li>    
                <li><a href="#">All rice's recipes</a></li>    
                <li class="dropdown"><a href="#"> Pasta</a>                 
                    <ul class="submenu">
                        <li><a href="#">Carbonara</a></li>    
                        <li><a href="#">Amatriciana</a></li>    
                        <li><a href="#">Al pesto</a></li>    
                        <li><a href="#">Pomodoro e basilico</a></li>    
                    </ul>
                </li>
                <li class="dropdown"><a href="#">Rice</a>                 
                    <ul class="submenu">
                        <li><a href="#">Milanese</a></li>
                        <li><a href="#">With mushrooms</a></li>
                        <li><a href="#">With peas</a></li>
                        <li><a href="#">With sea food</a></li>
                    </ul>
                </li>
            </ul>
        </li>
        <li class="dropdown"><a href="#">Steack</a>  
            <ul class="submenu">
                <li><a href="#">Stroganoff steaks</a></li>    
                <li><a href="#">Steak & chips</a></li>    
                <li><a href="#">Steak in red wine sauce</a></li>    
                <li><a href="#"> Horseradish butter steaks</a></li>
            </ul>
        </li>
        <li class="dropdown"><a href="#">Fishes</a>  
            <ul class="submenu">
                <li><a href="#">Smoky hake, beans & greens</a></li>    
                <li><a href="#">Grilled miso salmon with rice noodles</a></li>    
                <li><a href="#">Coconut fish curry</a></li>    
                <li><a href="#">Seafood tagine</a></li>    
            </ul>
        </li>
        <li class="dropdown"><a href="#">Fruits</a>  
            <ul class="submenu">
                <li><a href="#">Apricots in syrup with rosemary</a></li>    
                <li><a href="#">Black cherries cinnamon</a></li>    
                <li><a href="#">Caramelized pineapple with cream</a></li>    
            </ul>
        </li>
        <li class="dropdown"><a href="#">Desserts</a>  
            <ul class="submenu">
                <li><a href="#">Chocolate pudding</a></li>    
                <li><a href="#">Tuscan chestnut cake</a></li>    
                <li><a href="#">Hazelnut tart with fig jam</a></li>    
            </ul>
        </li>
    </ul>
</nav>     

Keep in mind you can add as many submenus as you need without change a single comma of the jquery code.

请记住, 您可以根据需要添加任意多个子菜单,而无需更改jquery代码的单个逗号。

使用jQuery (Go with jQuery)

What we want to do is to convert this simple list in a fully working Accordion menu.

我们要做的是在一个完全可用的手风琴菜单中转换此简单列表。

We want three things:

我们想要三件事:

  1. clicking on an item will open its submenu and clicking that item again will hide the submenu

    单击一个项目将打开其子菜单,再次单击该项目将隐藏该子菜单
  2. clicking on an item will hide any visible submenu before to show the submenu child of the clicked item

    单击一个项目将在显示被单击项目的子菜单子级之前隐藏任何可见的子菜单
  3. this mechanism must work respect any level of nested submenus (in the sample above we have three)

    此机制必须在任何级别的嵌套子菜单中都起作用(在上面的示例中,我们有三个)

Let's go to jQuery. First, we need to embed jQuery:

我们去jQuery。 首先,我们需要嵌入jQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

Is document ready?

文件准备好了吗?

$(document).ready(function (){ 

Now we have to attach an event handler to all anchor elements for the list items which have a submenu. We do this in two steps just to make it a bit more clear:

现在,我们必须将事件处理程序附加到具有子菜单的列表项的所有锚元素上。 我们分两步进行此操作,以使其更加清楚:

// first we get our accordion menu and we put it in the variable mymenu
var mymenu = $('ul#mg-accordion');
// then we create the variable dropdowns which holds all anchors children of list items of class 
// dropdowns. These anchors are the ones we have to attach the event handler to: clicking on them will how 
// the hidden submenu
var dropdowns = $(mymenu.find('li.dropdown > a')); 

And now the accordion code:

现在,手风琴代码为:

dropdowns.on('click', function (e) {
    //prevent default behavior
    e.preventDefault();
    // we are clicking on an anchor within a list item
    // so we find all ul.submenu elements which are
    // children of any list item which stays at the
    // same level of its parent
    var items = $(this).parents().siblings().find('ul.submenu');
    // for each found ul element we do the following
    items.each(function () {
        if ($(this).is(':visible')) {
            $(this).slideUp('slow');
        }
    });
    // show and hide lists
    $(this).siblings('ul.submenu').slideToggle();
}); 

If you want allow more than one submenu be visible at the same time you can just delete a few lines of code:

如果要允许同时显示多个子菜单,则只需删除几行代码即可:

var mymenu = $('ul#mg-accordion');
var dropdowns = $(mymenu.find('li.dropdown > a'));
dropdowns.on('click', function (e) {
    e.preventDefault();                             
    $(this).siblings('ul.submenu').slideToggle();
}); 


(
)

全部放在一起! (Putting it all together!)

That's all. You can style it as you prefer and you have no limit but your fantasy! :-)

就这样。 您可以根据自己的喜好为其设置样式,除了幻想之外,没有任何限制! :-)

Putting it all together we get the following code: this is exactly the same code you can see running above in my small accordion menu example.

全部放在一起,我们得到下面的代码:这是完全一样的代码,你可以看到运行上面我的小手风琴菜单的例子。

As you can see, I have added some code to put a + (plus) and - (minus) signs near to open and closed submenu and to change them accordingly to the user choices. See the comments in the code to learn more about this.

如您所见,我添加了一些代码以在打开和关闭子菜单附近放置一个+(加号)和-(减号)符号,并根据用户选择对其进行相应更改。 请参阅代码中的注释以了解有关此内容的更多信息。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Accordion test</title>
    <style>
      ul{
        list-style-type: none;                          
      }
      li.dropdown > ul{
        display: none;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-12">
          <nav class="my-menu">
            <ul id="mg-accordion"class="row"> 
              <li><a href="#" title="">All Italian Recipes</a></li>
              <li class="dropdown"><a href="#" title="">First courses</a>  
                <ul class="submenu">
                  <li><a href="#">All first courses</a></li>    
                  <li><a href="#">All pasta's recipes</a></li>    
                  <li><a href="#">All rice's recipes</a></li>    
                  <li class="dropdown"><a href="#"> Pasta</a>                 
                    <ul class="submenu">
                      <li><a href="#">Carbonara</a></li>    
                      <li><a href="#">Amatriciana</a></li>    
                      <li><a href="#">Al pesto</a></li>    
                      <li><a href="#">Pomodoro e basilico</a></li>    
                    </ul>
                  </li>
                  <li class="dropdown"><a href="#">Rice</a>                 
                    <ul class="submenu">
                      <li><a href="#">Milanese</a></li>
                      <li><a href="#">With mushrooms</a></li>
                      <li><a href="#">With peas</a></li>
                      <li><a href="#">With sea food</a></li>
                    </ul>
                  </li>
                </ul>
              </li>
              <li class="dropdown"><a href="#">Steack</a>  
                <ul class="submenu">
                  <li><a href="#">Stroganoff steaks</a></li>    
                  <li><a href="#">Steak & chips</a></li>    
                  <li><a href="#">Steak in red wine sauce</a></li>    
                  <li><a href="#"> Horseradish butter steaks</a></li>
                </ul>
              </li>
              <li class="dropdown"><a href="#">Fishes</a>  
                <ul class="submenu">
                  <li><a href="#">Smoky hake, beans & greens</a></li>    
                  <li><a href="#">Grilled miso salmon with rice noodles</a></li>    
                  <li><a href="#">Coconut fish curry</a></li>    
                  <li><a href="#">Seafood tagine</a></li>    
                </ul>
              </li>
              <li class="dropdown"><a href="#">Fruits</a>  
                <ul class="submenu">
                  <li><a href="accordion.php">Apricots in syrup with rosemary</a></li>    
                  <li><a href="#">Black cherries cinnamon</a></li>    
                  <li><a href="#">Caramelized pineapple with cream</a></li>    
                </ul>
              </li>
              <li class="dropdown"><a href="#">Desserts</a>  
                <ul class="submenu">
                  <li><a href="#">Chocolate pudding</a></li>    
                  <li><a href="#">Tuscan chestnut cake</a></li>    
                  <li><a href="#">Hazelnut tart with fig jam</a></li>    
                  <li class="dropdown"><a href="#">Desserts</a>  
                    <ul class="submenu">
                      <li><a href="#">Chocolate pudding</a></li>    
                      <li><a href="#">Tuscan chestnut cake</a></li>    
                      <li><a href="#">Hazelnut tart with fig jam</a></li>    
                      <li class="dropdown"><a href="#">Desserts</a>  
                        <ul class="submenu">
                          <li><a href="#">Chocolate pudding</a></li>    
                          <li><a href="#">Tuscan chestnut cake</a></li>    
                          <li><a href="#">Hazelnut tart with fig jam</a></li>    
                          <li class="dropdown"><a href="#">Desserts</a>  
                            <ul class="submenu">
                              <li><a href="#">Chocolate pudding</a></li>    
                              <li><a href="#">Tuscan chestnut cake</a></li>    
                              <li><a href="#">Hazelnut tart with fig jam</a></li>    
                            </ul>
                          </li>
                          <li class="dropdown"><a href="#">Desserts</a>  
                            <ul class="submenu">
                              <li><a href="#">Chocolate pudding</a></li>    
                              <li><a href="#">Tuscan chestnut cake</a></li>    
                              <li><a href="#">Hazelnut tart with fig jam</a></li>    
                            </ul>
                          </li>
                        </ul>
                      </li>
                      <li class="dropdown"><a href="#">Desserts</a>  
                        <ul class="submenu">
                          <li><a href="#">Chocolate pudding</a></li>    
                          <li><a href="#">Tuscan chestnut cake</a></li>    
                          <li><a href="#">Hazelnut tart with fig jam</a></li>    
                          <li class="dropdown"><a href="#">Desserts</a>  
                            <ul class="submenu">
                              <li><a href="#">Chocolate pudding</a></li>    
                              <li><a href="#">Tuscan chestnut cake</a></li>    
                              <li><a href="#">Hazelnut tart with fig jam</a></li>    
                            </ul>
                          </li>
                          <li class="dropdown"><a href="#">Desserts</a>  
                            <ul class="submenu">
                              <li><a href="#">Chocolate pudding</a></li>    
                              <li><a href="#">Tuscan chestnut cake</a></li>    
                              <li><a href="#">Hazelnut tart with fig jam</a></li>    
                            </ul>
                          </li>
                        </ul>
                      </li>
                    </ul>
                  </li>
                </ul>
              </li>
            </ul> 
          </nav>        
        </div>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
       $(document).ready(function () {
           var mymenu = $('ul#mg-accordion');
           var dropdowns = $(mymenu.find('li.dropdown > a'));
           dropdowns.each(function () {
               $(this).prepend('+ ');//we add a + (plus) symbol to highlight the fact that the node holds a submenu
           });
           dropdowns.on('click', function (e) {
               e.preventDefault();
               //Following 5 lines change the plus/minus symbols accordingly to the submenu state
               if ($(this).text().charAt(0) === '+') {
                   $(this).text($(this).text().replace('+', '-'));
               } else {
                   $(this).text($(this).text().replace('-', '+'));
               }
               var items = $(this).parents().siblings().find('ul.submenu');
               items.each(function () {
                   if ($(this).is(':visible')) {
                       $(this).slideUp('slow');
                       //we update plus/minus symbol in all siblings submenus 
                       $(this).siblings('.dropdown a').text($(this).siblings('.dropdown a').text().replace('-', '+'));
                   }
               });
               $(this).siblings('ul.submenu').slideToggle();
           });
       });
    </script>           
  </body>
</html> 

That's all, people. Hope this help :)

就这样,人们。 希望这个帮助:)

翻译自: https://www.experts-exchange.com/articles/21219/The-simplest-jQuery-Accordion-ever.html

jquery手风琴

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值