Home Web Front-end JS Tutorial Learning jQuery plug-in development starts with practice Menu plug-in development_jquery

Learning jQuery plug-in development starts with practice Menu plug-in development_jquery

May 16, 2016 pm 05:54 PM

Although this is not an advanced technique, it is still quite difficult for novices. If you are a novice, I hope you can learn something from this article; if you are an expert, I hope you can leave your valuable comments and suggestions

1. What plug-in should I use?
I want to implement a menu plug-in that can be used in websites or WEB application systems, has a flexible customized appearance, is simple, easy to use, easy to expand, and stable. It can be used on the main navigation bar of the website or in the management background.

2. What is the desired effect?
Usually the menu is in a collapsed state, and when the mouse is moved into it, its subordinate menu is displayed, and so on; you can conveniently use html tags to set the structure of the menu, or you can use an array to dynamically generate it.

3. Design functions

Description of the picture
The default state of the menu item.
The state when there is a lower-level menu and the mouse is moved into it.
Interval (for grouping effect)
Has a lower-level menu, the state when the mouse is not moved into it.
The vertical layout has a subordinate menu and the state when the mouse is moved into it.
The state when focus is obtained.
Other functions
The styles of all menu states are controlled through CSS and can be flexibly modified as needed.
Generate menus through HTML and javascript.
Specify the click callback function and jump address for the menu item (when specifying the callback function, the URL address is not set, but the URL address is passed into the callback function).
4. How to implement the function?
  1. Use CSS styles to control appearance.
  *In order to avoid CSS naming conflicts, we need to determine a namespace for the plug-in, and all styles under it will be under this namespace.
2. Selection of menu tags
* Generally speaking, most tags that implement menus will choose the list tag
, and we are no exception. .
Menu item:
  • Menu item display name

  • 3. Control How to display UL tags
    * Use CSS to remove symbols and indents
    * Use CSS to arrange horizontally. There are two ways to arrange horizontally:
    (1). The most commonly used one is floating arrangement (float: left;); But the biggest problem with this method is that it will destroy the page structure. I don't like this method very much.
    (2). Use the inline (display: inline-block) method; the currently known problem is that lower version browsers may not support it well. There are special articles discussing this problem on the Internet. Here I will No more details.
    *When I used this method, there was a small problem, that is, there was a gap of about 10px between the blocks. After I deleted the gaps (line breaks) between tags in the HTML code, these gaps disappeared. Although this solved the problem, it destroyed the structure of the code and made it less readable. It would still be acceptable if it was dynamically generated. So I thought of another solution, which is to set the left margin of each block (
  • tag) to -10px; and set the left inner margin of
      to 10px, perfect!!!
      5. Browser compatibility
      Relevant testing has not been conducted under IE6 and IE7.
      6. Function implementation and calling
      Style control
      Copy code The code is as follows:

      View Code
      /*In order to avoid naming conflicts, we put all styles of this plug-in under this class*/
      .ctcx-menu
      {
      font-size :14px;
      }
      .ctcx-menu ul
      {
      list-style-type:none;
      margin:0;
      padding:0;
      }
      /*Set offset*/
      .ctcx-menu ul.offset
      {
      position:relative;
      top:-32px;
      left:100px;
      }
      .ctcx-menu ul li /*Menu item style*/
      {
      width:100px;
      height:30px;
      line-height:30px;
      text-align:center ;
      vertical-align:top;
      margin:0;
      padding:0;
      }
      /*menu item style*/
      .ctcx-menu a
      {
      display:block;
      height:100%;
      border:1px solid #999;
      background-color:#FFF;
      text-decoration:none;
      color:# 000;
      }
      .ctcx-menu a:hover
      {
      background-color:#999;
      color:#FFF;
      }
      .ctcx-menu a :active{}
      /*Horizontal Menu*/
      .ctcx-menu .horizontal
      {
       padding-left:7px;
      }
      .ctcx-menu .horizontal li
      {
      display:inline-block;
      margin-left:-7px;
      }
      .ctcx-menu .horizontal li.item-has-children > a /*Have submenu Menu item style*/
      {
      }
      .ctcx-menu .horizontal li.spacing /*Horizontal spacing*/
      {
      height:30px;
      width:10px;
      background-color:#000;
      }
      /*vertical menu*/
      .ctcx-menu .vertical
      {
      }
      .ctcx-menu .vertical li
      {
      margin-left:0px;
      }
      .ctcx-menu .vertical li.item-has-children > a /*Menu item style with submenu*/
      {
      }
      .ctcx-menu .vertical li.spacing /*vertical spacing*/
      {
      height:10px;
      width:100px;
      background-color:# 000;
      }

      Plug-in code
      Copy code The code is as follows:

      View Code
      (function ($) {
          $.fn.menu = function (options) {
              if (typeof options != 'undefined' && options.constructor === Array) options = { data: options };
              var opts = $.extend({}, $.fn.menu.defaults, options);
              var _tempMenuData = [];
              //返回数据级别
              function getLevel(id) {
                  var _level = 0;
                  var _o = getMenuData(id);
                  while (_o != null) {
                      _level ;
                      _o = getMenuData(_o.pid);
                  }
                  return _level;
              }
              //返回数据对象
              function getMenuData(id) {
                  for (var i = 0; i < opts.data.length; i ) {
                      if (opts.data[i].id == id)
                          return opts.data[i];
                  }
                  return null;
              }
              //返回生成的HTML
              function getHtml(pid) {
                  var _li_data = getData(pid);
                  if (_li_data.length == 0) return null;
                  var _ul = $('
        ');
                    $.each(_li_data, function (i, _d) {
                        var _children = getHtml(_d.id);
                        var _li = $('
      • ').appendTo(_ul);
                        if (_d.n == null || _d.n.length == 0) {
                            _li.addClass('spacing');
                        } else if (typeof _d.fn === 'function') {
                            $('').html(_d.n)
                            .click(function () {
                                _d.fn(_d.url);
                            }).appendTo(_li);
                        } else if (_d.url.length > 0) {
                            $('').html(_d.n).appendTo(_li);
                        }
                        if (_children != null) {
                            _li.addClass('item-has-children');
                            _children.appendTo(_li);
                            _li.bind({
                                mouseover: function () {
                                    _children.show();
                                },
                                mouseout: function () {
                                    _children.hide();
                                }
                            });
                        }
                    })
                    if (pid == null && opts.type == 1) {
                        _ul.addClass('horizontal');
                    } else {
                        var _level = getLevel(pid);
                        _level > 0 && _ul.hide();
                        _ul.addClass('vertical');
                        if (_level > opts.type)
                            _ul.addClass('offset');
                    }
                    return _ul;
                }
                //返回下级数据数组
                function getData(pid) {
                    var _data = [];
                    _tempMenuData = $.grep(_tempMenuData, function (_d) {
                        if (_d.pid == pid) {
                            _data.push(_d);
                            return true;
                        }
                        return false;
                    }, true);
                    return _data;
                }
                return this.each(function () {
                    var me = $(this);
                    me.addClass('ctcx-menu');
                    if (opts.data != null && opts.data.length > 0) {
                        $.merge(_tempMenuData, opts.data);
                        me.append(getHtml(null));
                    }else {
                                                                                                                                                                                                                                                                                   . ;
        _ul.hide();
        self.bind({
        mouseover: function () {
                       _ul.show();
                          _ul.hide();                                                             } ); $.fn.menu.defaults = {
        type: 1, //The display mode of the menu (mainly refers to whether the first level is horizontal or vertical, the default is horizontal 1, vertical 0)
        /*
        data : Dynamically generate array data for the menu. If this data is specified, the menu will be filled with this data (the original data in the menu is replaced)
        Data format: [menu,menu,...]
        Menu object format: { id: 1, pid: null, n: 'Menu name 1', url: '#', fn: callback function}
                    */
                                                                                                         );


        Call JS code




        Copy code


        The code is as follows:

        View Code
        $(function () {
                              var _menuData = [
                                                                                                                                 . '#' },
        { id: 4, pid: null, n: 'Menu name 4', url: '#' },
        { id: 5, pid: null, n: 'Menu name 5' ', url: '#' },
                                                                                                                                                                                                                                                         'Menu name 7', url: '#' },
                                                                                                                                                         3, n: 'Menu name 9', url: '#' },
                                                                                                   11, pid: 9, n: 'Menu name 11', url: '#' },
                                                                             >                                                                                                                                                                                                                                             }. : 0, data: _menuData });
                                                                                                                                               🎜>

        HTML




        Copy code


        The code is as follows:

        View Code

                       

                             
        • 一级菜单1

        •                    
        • 一级菜单2

        •                    

        •                         一级菜单3
                                 

                                       
          • 二级菜单1

          •                            
          • 二级菜单2

          •                            
          • 二级菜单3

          •                            

          •                                 二级菜单4
                                           

                                                 
            • 三级菜单1

            •                                    
            • 三级菜单2

            •                                    
            • 三级菜单3

            •                                    
            • 三级菜单4

            •                                    
            • 三级菜单5

            •                                

                                       

          •                            
          • 二级菜单5

          •                        

                             

        •                    
        • 一级菜单4

        •                    
        • 一级菜单5

        •                

                   

                   

                   

                       

                             
        • 一级菜单1

        •                    
        • 一级菜单2

        •                    

        •                         一级菜单3
                                 

                                       
          • 二级菜单1

          •                            
          • 二级菜单2

          •                            
          • 二级菜单3

          •                            

          •                                 二级菜单4
                                           

                                                 
            • 三级菜单1

            •                                    
            • 三级菜单2

            •                                    
            • 三级菜单3

            •                                    
            • 三级菜单4

            •                                    
            • 三级菜单5

            •                                


          •                                                                         
            🎜> > ;/div>



            7. 다운로드

        여기를 클릭
        하여 사용 예시와 모든 파일을 다운로드하세요.
    • Statement of this Website
      The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

      Hot AI Tools

      Undresser.AI Undress

      Undresser.AI Undress

      AI-powered app for creating realistic nude photos

      AI Clothes Remover

      AI Clothes Remover

      Online AI tool for removing clothes from photos.

      Undress AI Tool

      Undress AI Tool

      Undress images for free

      Clothoff.io

      Clothoff.io

      AI clothes remover

      Video Face Swap

      Video Face Swap

      Swap faces in any video effortlessly with our completely free AI face swap tool!

      Hot Tools

      Notepad++7.3.1

      Notepad++7.3.1

      Easy-to-use and free code editor

      SublimeText3 Chinese version

      SublimeText3 Chinese version

      Chinese version, very easy to use

      Zend Studio 13.0.1

      Zend Studio 13.0.1

      Powerful PHP integrated development environment

      Dreamweaver CS6

      Dreamweaver CS6

      Visual web development tools

      SublimeText3 Mac version

      SublimeText3 Mac version

      God-level code editing software (SublimeText3)

      Hot Topics

      Java Tutorial
      1662
      14
      PHP Tutorial
      1261
      29
      C# Tutorial
      1234
      24
      Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

      JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

      The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

      The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

      JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

      Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

      JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

      JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

      How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

      This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

      Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

      Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

      From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

      The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

      Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

      I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

      See all articles