Home > Web Front-end > JS Tutorial > Javascript hand-made floating menu_javascript skills

Javascript hand-made floating menu_javascript skills

WBOY
Release: 2016-05-16 16:14:30
Original
1670 people have browsed it

Selectively reinventing some wheels is not necessarily a bad thing. A floating menu has been added to Aaron's blog, which seems to be very high-end. Although this is not the first time I have seen this kind of trick, I have never written it myself. Today I will selectively write about this function. The following is the development process of this wheel, which can also be regarded as the analysis and implementation process of a requirements document.

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

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

The first step is to create the DOM node structure:

Copy code The code is as follows:





AppCarrier




                                                                                                                                                                                                                        

test1


                  

The past can hurt. But you can either run from it or learn from it


                  

The past is painful, but you can either escape or grow from it


                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         “                                                                 

Rules are meant to be broken


               

Rules should be broken.


                  

Years may wrinkle the skin, but to give up enthusiasm wrinkles the soul.


& Lt; p & gt; The passage of years only makes the face old, and the passion no longer wither the heart.


                                                                                                                                                                                                                                                

test2


                                                                                                                                                                                                                        

Only by constantly practicing the knowledge you’ve learned can you truly master it.


                                                  

Live every day to the fullest.


Enjoy every day.


                                                                                                                                                                                                                                     & Lt; p & gt;


                                                                     

Always be up for an unexpected adventure.


& Lt; p & gt; ready to start an accidental adventure at any time.


                    

Life is full of disappointment. You can't dwell on things. You have to move on.


& Lt; p & gt; Life is often unsatisfactory, don't indulge in the past, go forward bravely.


                                               

I'm a free spirit. I can't be caged.


My soul is free and should not be bound.


                                                                                                                                                                                                                                             

Sometimes the heart sees what is invisible to the eye.


& Lt; P & gt; those who do not see the eyes, feel the heart & lt;/p & gt;
                        

The simple things are also the most extraordinary things, and only the wise can see them.


               

The most ordinary things are also the most extraordinary things, only the wise can understand.


                                                                                                                                                                                                                                          

test3


                                                                                                                                                                                                                     

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

test4


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


             

how many xxxxxx


   








The second step is to prepare the css file:


Copy code

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;
}
/*Suspended 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 floating menu*/
.slideIn {
Transform: translate3d(202px, 0, 0);
Transition-duration: .5s;
}
/*Display floating menu*/
.slideOut {
Transform: translate3d(0, 0, 0);
Transition-duration: .5s;
}
.static {
Color:#007aff;
Text-align: center;
}
/*Display 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: 1s;
}



The third step is to start writing js code:


Copy code

The code is as follows:

(function(doc){
//Collect the link locations of each chapter
var pos = [],
​​​​ //Collect items on the menu
          links = doc.getElementsByTagName('a'),
//Collect chapter titles
titles = doc.getElementsByTagName('h1'),
//Suspended menu
           menu = doc.getElementById('menubar'),
//Current selection
           currentItem=null;
//Add red style
var addClass = function (element){
                  currentItem && currentItem.removeAttribute('class');
                element.setAttribute('class','red');
                  currentItem = element;
         },
// The webpage is rolled high:
         getScrollTop = function (){
               return Math.ceil(document.body.scrollTop) 1;
},
//Calculate scroll position
StartScroll = function (){
            var scrollTop = getScrollTop(),
                   len = titles.length,
                  i = 0;
//Article 1
If(scrollTop>=0 && scrollTop                    addClass(links[0]);
                  return;
            }
// Last <条> If(scrollTop>=pos[len-1]){
                    addClass(links[len-1]);
                  return;
            }
// In the middle for(;i If(scrollTop > pos[i] && scrollTop < pos[i 1]){
                      addClass(links[i]);
break;
                }
            }
};
//Click a link in the list to change color
menu.onclick=function(e){
        var target = e.target || e.srcElement;
If(target.nodeName.toLowerCase() === 'a'){
//List item status indication
               addClass(target);
              return;
         }
If(target.nodeName.toLowerCase() === 'p'){
If(target.className == 'static'){
//Hide menu
This.className = 'menu slideIn';
                    setTimeout(function(){
                                target.className = 'static toShow';
Target.innerHTML = 'Display';
                   },1000);
                }else{
//Show menu
                         target.className = 'static';
                        target.innerHTML = 'Hide';
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 to scroll
​ window.onscroll = function(){
StartScroll()
}
})(document);

Analysis:

1. Automatically jump to the specified section

This step can be done by using the anchor function of the tag. Since HTML5 does not support the name attribute in the future (HTML5 does not support it. Specify the name of the anchor.), so consider using ID to jump.

2. Identify which chapter in the content on the left the item in the floating menu belongs to.

This step is difficult, let’s briefly analyze it first:

2.1 The first situation is to click on the menu item manually. This is easy, just identify the clicked element.

2.2 In the second case, scroll through the middle mouse button or drag the scroll bar. At this time, you need to associate the content on the left with the menu items on the right. This is the most difficult part. Consider a strategy of implementing it step by step, starting with the easier and then the harder, and defeating them one by one.

2.2.1 First collect the coordinate height of the title element. That is the vertical height of all h1 tags. Store in array 1.

2.2.2 Collect the a elements in the menu items and store them in array 2.

2.2.3 Listen to scroll events and determine which menu item the current content belongs to.

When doing a step, it is recommended to draw a picture on the manuscript paper:

A1

******************
                                                                                                    *
                                                                                                                                                                                                                                                   *
                                                                                                                                           *
                                                                                                 *

Every time you scroll, determine which interval the current scrolling distance is. If it is 0 to A1, it is Chapter 1, A1 to A2 is Chapter 2, and so on.

About the position and height of the element, I simply use element.offsetTop to get it. There may be compatibility issues. If you use jquery to do it, it should be $('element').offset().top,

Similarly, the height of the rolling bar, I also simply used the document.body.scrolltop to get it. If it is replaced with jquery, it should be $ (window). Scrolltop ();

The function of drawing is to make abstract problems concrete and help us think and find out the rules. Maybe calling it "modeling" would be a bit more noble.

It should be emphasized that the relationship between array 1 and array 2 should be one-to-one correspondence. For example,
corresponds to

.

2.3 The third case is the menu status indication when entering the page directly. For example, when entering through an address such as index.html#h3, h3 in the menu should be highlighted.

3. Implement the display and hiding animation of the floating menu.

3.1 This step should be relatively simple, so you can consider doing it first. Just use the tramsform attribute of CSS3. It is simple and efficient. If it is cross-browser, pay attention to compatibility.

Pay attention to transform: translate3d(x-axis, y-axis, z-axis); Using 3D, you can use hardware acceleration to increase animation effects, but the power consumption will increase, so make good use of it! The first parameter controls the left and right direction. If it is positive, it means moving to the right. If it is negative, it means moving to the left. This is actually not rigorous. In fact, it should be determined based on the reference point. For example, the x coordinate of the element when it is at rest is 0, then increase the value of x to the right, decrease to the left, and 0 is reset.

After the analysis, it’s time to write the code. There is nothing to say about this. Enjoy the musicality of typing on the keyboard.

After finishing writing, preview it, click on the menu, jump to the specified chapter, and click on the item to turn red, refresh the current page, and the dependencies will be displayed correctly. Slide the scroll wheel, and the menu items will change accordingly as the content changes. Drag the scroll bar, and the same is true. Finally, click to hide, and the menu will retract. Click to show, and the menu will slide out. This completes the floating function.

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

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template