Realization of Baidu News navigation menu sliding animation _jquery based on jquery

Source: Internet
Author: User

This example for you to share jquery Baidu News navigation menu slide animation, for your reference, the specific content as follows

Thoughts and steps
1. Use the UL to create the simple transverse navigation;

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

2. Add a detached div, named Div-hover, 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 element of the div-hover, the left, the top margin and the width;

<script type= "Text/javascript" >
  var divhoverleft = 0;
  var awidth = 0;

  $ (document). Ready (function () {
    $ ("a"). On ({
      ' mouseover ': function () {
        setdivhoverwidthandleft (this);
        Sets the slide animation
        $ (". Div-hover"). Stop (). 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's 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 to left;
 }
</script>

Effect Preview

From the preview effect can be seen, div-hover positioning is problematic, div-hover should be the parent element absolute positioning, so modify the code (Annotation section is modified point) as follows:

<style type= "Text/css" >
  div-nav
  {
    width:870px;
    margin:0px Auto;
    /* Position Reference as parent element of Div-hover
    /position:relative
  ;
  Div-hover
  {
    background-color:red;
    height:50px;
    left:0px;
    top:0px;
    width:0px;
    /* With the parent element absolute positioning *
    /position:absolute;
  }
</style>

Although the positioning problem is resolved, but 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 floats 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 () {setdivhoverwidthandleft (this);
      Sets the slide animation $ (". Div-hover"). Stop (). Animate ({width:awidth, left:divhoverleft}, 150);
        * * Add click event/' click ': function () {setdivhoverwidthandleft (this);
        Clears all a tag class $ (' a '). Removeclass ();
      Set the current click menu to activate the status $ (this). addclass (' active ');
  }
    });
}); </script>  

Effect Preview

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

Before doing this function, the first idea, the mouse out of the operation, we can think of mouseout,mouseleave events, then there will be the following several questions:

① this place to choose which event can satisfy this condition?

② which element is the chosen event positioned again?

③ How do you know which element is active after moving out of the mouse?

How does ④ know the left margin and width equivalent 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? Through the above GIF, analysis, if positioned in a label or Li tag, then the mouse move out of a label or the LI tag switch will also trigger the automatic positioning to the activation element (assuming that automatic positioning has done), it will appear as shown in the following figure:

So you can't position it on a or Li tag, think again, the mouse should be moved out of the entire range of navigation, then locate in which element is very easy to come out, should be positioned in the UL or UL parent elements, their size range is consistent, so two elements can be, if two elements of inconsistent size, Should be positioned on the UL above. So there is a code similar to the following:

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

Then, how to know what the current activation elements, you can click on the event, using hidden fields or other display methods 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, and thus solve the above ③④ problem;

(Of course, want to know menu activation element, also can use class for active way to find, but this way, relatively troublesome, first get active element, and then through Li, recalculate width and left margin, and finally to assign value and add sliding positioning; Take up the hidden field mode to handle, because it is convenient and simple, the group of friends if interested can be used in active mode test)

<script type= "Text/javascript" > var divhoverleft = 0;

   var awidth = 0; $ (document). Ready (function () {//Menu slide animation $ ("a"). On ({' MouseOver ': function () {Setdivhoverwidtha
         Ndleft (this);
       Sets the slide animation $ (". Div-hover"). Stop (). Animate ({width:awidth, left:divhoverleft}, 150);
         ' Click ': function () {setdivhoverwidthandleft (this);
         Clears all a tag class $ (' a '). Removeclass ();
         Set the current click menu to activate the status $ (this). addclass (' active ');
         $ (". H-width"). Val (awidth);
       $ (". H-left"). Val (Divhoverleft);

     }
     }); /* Mouse slip out of UL or Div-nav background div-hover automatically positioned to activate the menu/$ ("ul"). On ({' Mouseout ': function (event) {$ (". Div-hover").
       Stop (). Animate ({width: $ (". H-width"). Val (), Left: $ (". H-left"). Val ()}, 150;
  }
     });

  });
    function Setdivhoverwidthandleft (element) {divhoverleft = GetLeft (Element);
  Awidth = getwidth (Element); ... </script> <..../head> <body> <div class= "Div-nav-container" > <div class= "Div-nav" > <!--add sliding background--> <div class= "Div-hover" > </div> <ul> <li><a class= "Active href=" JAVASC Ript:void (0) "> website home </a></li> ... </ul> </div> </div> <inp
UT type= "hidden" class= "H-width" value= ""/> "<input" type= "hidden" class= "H-left" value= "0"/> </body>

  

Effect Display:

The reason for this is that the figure finds a problem similar to the position of a or Li before it appears:

jquery mouseout If positioned on an element, such as Div, then the elements under this div will have mouseout events, which is often said, event bubbling mechanism; similar events such as Mousedown,mouseover, So is it okay to stop the event bubbling? This is theoretically the case. There are usually two ways to block Bubbles: event.stoppropagation () and return false; There is a difference between them, of course.

The relevant code is modified as follows:

<script type= "Text/javascript" >

    ..... $ (document). Ready (function () {/
 
      * mouse slide out of UL or Div-nav background div-hover automatically locate to activation menu
      /$ ("ul"). On ({
        ' mouseout ': function (event) {
          $ ('. Div-hover '). Stop (). Animate ({width: $ (". H-width"). Val (), Left: $ (". H-left"). Val ()}, 150; c7/>/** prevents bubbling **/
          event.stoppropagation ();
          return false;

    }}); .......
</script>

No matter what kind of blocking, there is no egg, still can not stop bubbling, the effect is conceivable, and the above GIF figure is no different;

This proves that mouseover is problematic in implementing this function;

Then change the MouseLeave, in addition to MouseOver modified to MouseLeave and remove bubbling code, the other code does not make changes, the experimental results are as follows:

From the above figure can be seen, the effect and Baidu News navigation is basically the same, this is accomplished;

Complete code

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

Summary and key points
1. The background slide is implemented by a block element (the div used here), rather than the hover of this element to change the background color;

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

3. Slide animation event animate and record activation menu, mouse to move out of the region to navigate to the activation menu;

4.jquery the difference between mouseover,mouseout and mouseenter,mouseleave about the bubbling mechanism; (the first two have no bubbling mechanisms, the last two bubbles have been processed, and the events are only for the registered element itself, not the child element, MouseEnter and MouseLeave used in an element tag can be replaced by the hover event, itself hover is the encapsulation of both, if the event on the different elements of the label, it is best to separate call MouseEnter and MouseLeave events)

5. All the key points and roles have been annotated throughout the code, as you can see.

I hope this article will help you learn the jquery program.

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.