Navigation Menu Slide Animation

Source: Internet
Author: User

Objective

Two days ago, a group of people asked how Baidu news navigation is realized, at that time because of busy work, did not have time to see, just today there is free, simply to achieve this effect it;

Ideas and steps

1. Use UL to create simple horizontal navigation;

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

2. Add an off-layer Div, name div-hover, use for menu sliding animation, set CSS style;

<style type= "Text/css" >   . div-hover   {      background-color:red;height:50px;      left:0px;      top:0px;      width:0px;
   }</style><div class= "Div-nav" >     <!--add sliding background--     <div class= "Div-hover" >     < /div>     <ul> ...     </ul></div>

3. Add the Slide event of the menu item, calculate the sliding features of the div-hover, left, top margin and width;

Implementation code

<script type= "Text/javascript" >    var divhoverleft = 0;    var awidth = 0;    $ (document). Ready (function () {        $ ("a"). [{           ' mouseover ': function () {               setdivhoverwidthandleft (this);               Set slide animation               $ (". Div-hover"). Animate ({width:awidth, left:divhoverleft}, ()});})   ;   function Setdivhoverwidthandleft (Element) {       Divhoverleft = GetLeft (element);       Awidth = getwidth (Element);   }   Get Li width   function getwidth (ele) {      return $ (ele). Parent (). width ();   }   Get div-hover left margin   function GetLeft (element) {     //Get Li before the sibling Li element     var menulist = $ (Element). Parent (). Prevall ();     var left = 0;     Calculates the background matte left margin      $.each (menulist, function (index, ele) {Ieft        + + $ (ele). width ();     });     return left;  } </script>

Effect Preview

As can be seen from the preview effect, Div-hover's positioning is problematic, div-hover should be absolutely positioned with the parent element, so the modified code (the comment section is the modification point) is as follows:

<style type= "Text/css" >    . Div-nav    {       width:870px;       margin:0px Auto;       /* As parent element of Div-hover, locate reference */       position:relative;    }    . Div-hover    {       background-color:red;       height:50px;       left:0px;       top:0px;       width:0px;       /* Absolute positioning of the parent element */       position:absolute;    } </style>

Although the positioning problem is resolved, the background image is still floating above the text, so adjust the code to float the text above the red div:

<style type= "Text/css" >   ul li   {       float:left;        /*****start (function: Navigation text floating above div-hover red) *******/       position:relative;       Z-index:4;        /*********************end*************************/   }</style>

Effect Preview

4. Add menu click, and Load page default menu selected;

 <style type= "Text/css" >/** settings menu activates ***/. active {background-color:red;   }</style><script type= "Text/javascript" > var divhoverleft = 0;   var awidth = 0; $ (document). Ready (function () {$ ("a"). On ({' MouseOver ': function () {Setdivhoverwidthandle               FT (this);            Set the slide animation $ (". Div-hover"). Animate ({width:awidth, left:divhoverleft}, 150);                },/* Add Click event */' click ': function () {setdivhoverwidthandleft (this);                Clears all a label class $ (' a '). Removeclass ();            Sets the current Click menu to the active state $ (this). addclass (' active ');   }       });            });</script>
                <li><a class= "Active" href= "javascript:void (0)" > Homepage </a></li> .....                
            </ul>        </div>    </div></body>

Effect Preview

5. Add mouse to move out the range, automatically locate the current activation element function;

Before doing this function, the first thought, the mouse move out of the operation, we can think of Mouseout,mouseleave event, then there will be the following several questions:

① which event does this place use to satisfy this condition?

② which element does the selected event locate?

How do you know which element is currently active when ③ is moved out of the mouse?

How does ④ know the left margin and width of div-hover?

Practice the truth, then practice:

First of all, take mouseout as an example, the first problem is solved naturally;

Second, which element is the event positioned on? With the above GIF, analysis, if positioned on a label or li tag , then the mouse out operation between a tag or Li tag will also trigger the automatic positioning to the activation element ( assuming that the automatic positioning has been done ), will appear as shown in the situation:

So can not be located on A or Li label , think again, the mouse should be moved out of the entire range of navigation can be, then positioning in which element is easy to come out, should be located in the UL or ul of the parent element, they both size range is consistent, So two elements can be, if the size of two elements are inconsistent, it should be positioned on the UL above. So there's a code like this:

$ ("ul"). On ({      ' mouseout ': function (event) {/            * * Animate positioning Div-hover position to active element */       }});

Then, how to know the current activation of the element, you can click on the event, with a hidden field or other display mode to store the current click of the element width and left margin, to move the mouse out of the operation, re-read the stored data, and then animate positioning, so as to solve the above ③④ problem; Part of the code is as follows:

(Of course, want to know the menu activation element, you can also use the class for the active way to find, but this way, relatively troublesome, first get active elements, and then by traversing Li, re-calculate the width and left margin, finally to assign value and add sliding positioning; Take a hidden domain approach here because it is convenient and easy, and if you are interested, you can experiment with active mode.

 <script type= "Text/javascript" > var divhoverleft = 0;     var awidth = 0;                 $ (document). Ready (function () {//Menu slide animation $ ("a"). On ({' MouseOver ': function () {                 Setdivhoverwidthandleft (this);             Set the slide animation $ (". Div-hover"). Animate ({width:awidth, left:divhoverleft}, 150); }
' Click ': function () {setdivhoverwidthandleft (this);                 Clears all a label class $ (' a '). Removeclass ();                 Sets the current Click menu to the active state $ (this). addclass (' active ');                 $ (". H-width"). Val (awidth);             $ (". H-left"). Val (Divhoverleft);         }         }); /* Mouse slide out of UL or Div-nav background div-hover automatically navigate to the Activation menu */$ ("ul"). On ({' Mouseout ': function (event) {$              (". Div-hover"). Animate ({width: $ (". H-width"). Val (), Left: $ (". H-left"). Val ()}, 150);    }         });    });        function Setdivhoverwidthandleft (element) {divhoverleft = GetLeft (Element);    Awidth = getwidth (Element); } .... </script>
  
  

Effect Show:

Look at the figure shows that there is still a problem similar to locating in a or Li before, the reason for this situation:

jquery in Mouseout if positioned on an element, such as a Div, then the elements under this div will have mouseout events, which is often said, event bubbling mechanism, similar events such as Mousedown,mouseover, etc. so is it OK to stop the event bubbling? theoretically. There are usually two ways to block bubbling: event.stoppropagation (); and return false; Of course they are also different, about the difference can be stamped: http://blog.csdn.net/JeamKing/ article/details/5332328/;

The relevant code is modified as follows:

<script type= "Text/javascript" >        .... $ (document). Ready (function () {/             * mouse slides out of UL or Div-nav background div-hover automatically navigates to the activation menu */            $ ("ul"). On ({                ' mouseout ': function (event) {                    $ (". Div-hover"). Animate ({width: $ (". H-width"). Val (), Left: $ (". H-left"). Val ()}, ();                    /** block bubbling **/                    event.stoppropagation ();                    return false;       }); .......
</script>

No matter what kind of blocking method, there is no egg, still can't stop bubbling, the effect can be imagined, and the above GIF picture is the same;

This proves that MouseOver has problems in realizing this function;

That change MouseLeave , in addition to change the mouseover to MouseLeave and remove bubbling code, other code does not make changes , the experiment effect is as follows:

As can be seen, the effect and Baidu news navigation sliding Basically the same, this is accomplished;

Full code

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
                 /* Here with mouseover or MouseEnter, if you want to add hover and move out events for the x tag at a later time, it is recommended to use enter and leave, which is the legendary hover event, because the event bubbling has already been processed, there will be no similar over and                    Out or something. */' MouseEnter ': function () {setdivhoverwidthandleft (this);                Set the slide animation $ (". Div-hover"). Animate ({width:awidth, left:divhoverleft}, 150);                    }, ' click ': function () {setdivhoverwidthandleft (this);                    Clears all a label class $ (' a '). Removeclass ();                    Sets the current Click menu to the active state $ (this). addclass (' active ');                    $ (". H-width"). Val (awidth);                $ (". H-left"). Val (Divhoverleft);            }            });                /* Mouse slide out of UL or Div-nav background div-hover automatically navigate to the Activation menu *///mouseleave event location to UL or Div-nav can be $ ("ul"). On ({ ' MouseLeave ': function (event) {$ (". Div-hover"). Animate ({width: $ (". H-width"). Val (), Left: $ (". H-left "). Val ()}, 150);        }            });        });            function Setdivhoverwidthandleft (element) {divhoverleft = GetLeft (Element);        Awidth = getwidth (Element);        }//Get Li width function getwidth (ele) {return $ (ele). Parent (). width (); }//Get Div-hover left margin function GetLeft (element) {//Get Li before the sibling li element var menulist = $ (elemen            T). Parent (). Prevall ();            var left = 0;          Calculates the background matte left margin $.each (menulist, function (index, ele) {Ieft + + $ (ele). width ();          });        return left;            } </script>

Summary and key points

1. The background slide is implemented by a block element (the div used here), not the hover of this element to change the background color;

2. Attention to the element positioning (the slider is the most important to the absolute positioning or relative positioning, the calculation of the left margin and the calculation of its own width, sliding block elements div-hover and Li relative positioning, as well as the level of size);

3. Slide the animated event animate and record the activation menu, the mouse moves out of the area to customize the positioning to the activation menu;

The difference between mouseover,mouseout and mouseenter,mouseleave about the bubbling mechanism in 4.jquery , (the first two bubbles are not limited, the last two bubbling has been processed, the event is only for registering the element itself, Instead of working with the child elements, MouseEnter and MouseLeave are used on an element tag to replace the hover event, which is itself hover the encapsulation of the two, if the event is on a different element label, Preferably separate calls to MouseEnter and MouseLeave events )

5. All key points and roles have been annotated throughout the entire code, and you can look at them.

Finally, if you find that the article has errors or omissions, the message, in the next grateful, if there is a group of friends on the JS mouse events (mouseup,mousedown,mouseover,mouseout, etc.) and jquery about the difference between these events interested in, Also please tell, I have time to sort out another blog, I hope this blog can play a role;

Navigation Menu Slide Animation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.