Objective
When the top of the page menu is, the use of the anchor jump method is easy to block the content you want to render (such as the skill two characters are blocked half), in order to avoid such problems, so scroll to the specified element using JS method to achieve.
1 Introduction to the API used
2 First Edition
- The code and ideas are as follows:
//1 Click to navigate to the specified location first step, get all the A tagsLet Atags=document.queryselectorall ("Nav.menu ul Li a") //Console.log (atags)//2 Click the navigation to jump to the specified position the second step to traverse a label for(Let i=0; i<=atags.length;i++) {Atags[i].onclick=function(x) {x.preventdefault (); //Block A-tab default jump//Console.log (x.currenttarget);Let a=X.currenttarget; Let href=a.getattribute ("href");//find the content in the href if an anchor point in the href returns #siteskill//console.log (href);Let element=document.queryselector (HREF);//find the label of the anchor point corresponding ID in the content, if the corresponding anchor name is #siteskill, then return <section class=? " Skills "Id=?" Siteworks ">?...? </section>? //Console.log (element);Let Top=element.offsettop;//gets the height of the element to the top of the page (does not change as the page scrolls)//Console.log (top);Window.scrollto (0, top- the); }}
- As follows
- This can accurately reach the desired place and will not be blocked, but there are some shortcomings, such as jump too blunt, there is no transition in the middle, affecting the user experience.
3 optimization
- The optimized code is as follows:
//1 Click to navigate to the specified location first step, get all the A tagsLet Atags=document.queryselectorall ("Nav.menu ul Li a") //Console.log (atags)//2 Click the navigation to jump to the specified position the second step to traverse a label for(Let i=0; i<=atags.length;i++) {Atags[i].onclick=function(x) {x.preventdefault (); //Block A-tab default jumpLet a=X.currenttarget; Let href=a.getattribute ("href");//find the content in the href if an anchor point in the href returns #siteskillLet element=document.queryselector (HREF);//find the label of the anchor point corresponding ID in the content, if the corresponding anchor name is #siteskill, then return <section class=? " Skills "Id=?" Siteworks ">?...? </section>?Let top=Element.offsettop; Let N= -;//Number of movesLet t= -/n;//How often do you move?Let currenttop=window.scrolly;//Where you areLet targettop=top- the;//Target Locationvar s= (targettop-currenttop)/n;//distance of each moveLet i=0; LetID=setinterval (() ={ if(i===N) {Window.clearinterval (ID); Return } //Stop animation when I=ni=i+1Window.scrollto (0, currenttop+s*i)},t)}
Make the page scroll to the specified element + optimization +api Introduction (JS animation)