Javascript-hand-made floating menu

Source: Internet
Author: User

Javascript-hand-made floating menu

This article mainly introduces how to manually create a suspended menu by using javascript. I also want to practice the menu by myself. It feels pretty good. I recommend it to you here.

 

 

It may not be a bad thing to selectively duplicate some wheels. Aaron added a floating menu to his blog, which seemed very high. Although this kind of trick is not the first time you see it, you have never written it yourself. Today, we will choose to write this function. The following is the development process of this wheel. It can also be considered as the analysis and implementation process of a requirement document.

Demo address: http://sandbox.runjs.cn/show/to8wdmuy

Source code download: https://github.com/bjtqti/floatmenu

Step 1: Create a dom section:

 

The Code is as follows:


<! DOCTYPE html>
<Html>
<Head>
<Meta charset = "UTF-8">
<Title> AppCarrier </title>
<Link rel = "stylesheet" href = "menu.css">
</Head>
<Body>
<Div id = "content">
<H1 id = "test1"> test1 <P> The past can hurt. But you can either run from it or learn from it </p>
<P> the past is painful, but you can either escape or grow from it </p>
<P> One meets his destiny on the road he takes to avoid it </p>
<P> often on the road to escaping fate, but it is not expected to happen. </p>
<P> Rules are meant to be broken </p>
<P> the rule should be broken. </P>
<P> Years may wrinkle the skin, but to give up enthusiasm wrinkles the soul. </p>
<P> the passage of time only makes the appearance old, passion no longer makes the soul withered. </P>
<H1 id = "test2"> test2 <P> You can grasp the learned knowledge only by continuously practicing it. </P>
<P> Live every day to the fullest. </p>
<P> enjoy the day. </P>
<P> Keep your eyes on the stars, and your feet on the ground. </p>
<P> high-minded, down-to-earth. </P>
<P> Always be up for an unexpected adventure. </p>
<P> Start an unexpected adventure at any time. </P>
<P> Life is full of disappointment. You can't dwell on things. You have to move on. </p>
<P> life is always unsatisfactory. do not indulge in the past and go forward. </P>
<P> I'm a free spirit. I can't be caged. </p>
<P> my soul is free and should not be bound. </P>
<P> Sometimes the heart sees what is invisible to the eye. </p>
<P> invisible, perceptible </p>
<P> The simple things are also the most extraordinary things, and only the wise can see them. </p>
<P> the most common thing is also the most extraordinary thing. Only wise men can understand it. </P>
<H1 id = "test3"> test3 <P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<H1 id = "test4"> test4 <P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
<P> how many xxxxxx </p>
</Div>
<Div class = "menu" id = "menubar">
<P class = "static"> hide </p>
<Ul>
<Li> <a href = "# test1"> test1 </a> </li>
<Li> <a href = "# test2"> test2 </a> </li>
<Li> <a href = "# test3"> test3 </a> </li>
<Li> <a href = "# test4"> test4 </a> </li>
</Ul>
</Div>
</Body>
<Script src = "menu. js"> </script>
</Html>

 

Step 2 prepare the css file:

 

The Code is as follows:


Ul {
List-style-type: none;
}
A {
Text-decoration: none;
}
/* Article content area */
# Content {
Width: 400px;
Margin: 0 auto;
Font-size: 2em;
}
/* Floating menu */
. Menu {
Position: fixed;
Top: 20%;
Right: 0;
Width: 200px;
Border: 1px solid gray;
Border-radius: 5px;
}
. Menu li {
Height: 2em;
Line-height: 2em;
}
. Red {
Color: red;
}
. Hide {
Display: none;
}
/* Hide the suspended menu */
. SlideIn {
Transform: translate3d (202px, 0, 0 );
Transition-duration:. 5 s;
}
/* Display the suspended menu */
. SlideOut {
Transform: translate3d (0, 0, 0 );
Transition-duration:. 5 s;
}
. Static {
Color: # 007aff;
Text-align: center;
}
/* Display the suspended ball */
. ToShow {
Display: block;
Width: 4.8em;
Height: 2em;
Line-height: 2em;
Border-radius:. 5em;
Border: 1px solid gray;
Transform: translate3d (-5em, 0, 0 );
Transition-duration: 1 s;
}

 

Step 3: Write the js Code:

 

The Code is as follows:


(Function (doc ){
// Collect the links of each chapter
Var pos = [],
// Collect items from the menu
Links = doc. getElementsByTagName ('A '),
// Collect chapter titles
Titles = doc. getElementsByTagName ('h1 '),
// Floating menu
Menu = doc. getElementById ('menubar '),
// Currently selected items
CurrentItem = null;
// Add a red style
Var addClass = function (element ){
CurrentItem & currentItem. removeAttribute ('class ');
Element. setAttribute ('class', 'red ');
CurrentItem = element;
},
// The height of the webpage being rolled:
GetScrollTop = function (){
Return Math. ceil (document. body. scrollTop) + 1;
},
// Calculate the scroll position
StartScroll = function (){
Var scrollTop = getScrollTop (),
Len = titles. length,
I = 0;
// The first
If (scrollTop> = 0 & scrollTop <pos [0]) {
AddClass (links [0]);
Return;
}
// The Last One
If (scrollTop> = pos (len-1]) {
AddClass (links [len-1]);
Return;
}
// Intermediate
For (; I <len; I ++ ){
If (scrollTop> pos [I] & scrollTop <pos [I + 1]) {
AddClass (links [I]);
Break;
}
}
};
// Click the link in the list to change color.
Menu. onclick = function (e ){
Var target = e.tar get | e. srcElement;
If (target. nodeName. toLowerCase () = 'A '){
// List item status indication
AddClass (target );
Return;
}
If (target. nodeName. toLowerCase () = 'P '){
If (target. className = 'static '){
// Hide the menu
This. className = 'menu slidein ';
SetTimeout (function (){
Target. className = 'static toShow ';
Target. innerHTML = 'display ';
},1000 );
} Else {
// Display menu
Target. className = 'static ';
Target. innerHTML = 'hiding ';
This. className = 'menu slideout ';
}
}
}
// Calculate the initial position of each chapter
Var ln = titles. length;
While (-- ln>-1 ){
// Titles [len]. offsetParent. offsetTop = 0;
Pos. unshift (titles [ln]. offsetTop );
}
StartScroll ();
// Listen for scrolling
Window. onscroll = function (){
StartScroll ()
}
}) (Document );

 

Analysis:

1. automatically jump to a specified section

In this step, you can use the <a> tag's anchor function. Because html5 does not support the name attribute in the future (html5. Specifies the name of the anchor .), So use ID to jump.

2. Identify which chapter in the left content the items in the suspended menu belong.

This step is difficult. Let's analyze it briefly:

2.1 The first case is to manually click the menu item. This is easy. You only need to identify the clicked element.

2.2 In the second case, you can scroll or drag the scroll bar through the middle mouse. In this case, you need to associate the left content with the right menu items, which is the most difficult part. Consider step-by-step implementation, which is easy and difficult to crack.

2.2.1 collect the coordinates of the title element first. That is, the vertical height of all h1 labels. Save to array 1.

2.2.2 collect the element from the menu and store it in an array. 2.

2.2.3 listen for Rolling events and determine which menu item the current content belongs.

We recommend that you draw a picture on the paper as follows:

A1

****************
* A2
*
****************
* A3
*
****************
*
* A4
*

Each time it is rolled, it determines the range of the current rolling distance. If it is 0 to A1, It is Chapter 1st, Chapter 2nd from A1 to A2, and so on.

For the position and height of an element, here I simply use element. offsetTop can be obtained, and there may be compatibility issues. If jquery is used, it should be $ ('element '). offset (). top,

Similarly, I used document. body. scrollTop to retrieve the height of the scroll bar. If jquery is used, it should be $ (window). scrollTop ();

The role of plotting is to embody abstract problems, help us to think about and find out patterns. Maybe "modeling" will look very tall.

The relationship between array 1 and array 2 must be one-to-one. For example, <a href = "# h1"> corresponds to

2.3 In the third case, the menu status indication when you enter the page directly. For example, if you access the address index.html # h3, the h3 in the menu should be highlighted.

3. Display and hide the suspended menu.

3.1 this step should be relatively simple and can be considered first. You can use the tramsform attribute of css3. It is simple and efficient. If it is cross-browser, pay attention to compatibility.

Note: transform: translate3d (X axis, Y axis, and Z axis). With 3d, you can use hardware acceleration to increase the animation effect, but the power consumption will increase! The first parameter controls the left and right directions. If it is positive, it indicates moving to the right. If it is negative, it moves to the left. In this case, it is not rigorous. In fact, it should be determined based on the reference point. For example, if the x coordinate of an element is 0 at rest, increase the value of x to the right and reduce it to the left, 0 is reset.

After the analysis, you can write the code. There is nothing to say. Enjoy the pleasure of hitting the keyboard.

After writing the content, Preview It, click the menu, jump to the specified chapter, and click the item to red to refresh the current page. The dependency is correctly displayed. Slide the scroll wheel and the menu items change accordingly as the content changes. Drag the scroll bar to hide the menu items. Click hide to hide the menu items. Click Show to display the menu items. This completes the suspension function.

The above is all the content of this article. I hope you will like it.

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.