JQuery implements smooth scrolling of anchor links
In normal projects, we often need special effect links. If the effect is further enhanced, We can smoothly scroll to the anchor by clicking the anchor link, the following describes how to use jQuery.
Generally, when you use an anchor to jump to a specified position on a page, the page will jump to the specified position immediately, but sometimes we want to smoothly transition to the specified position, JQuery can be used to achieve this effect simply:
For example, we will click the tag to jump to the specified position where id is content.
?
| 1 |
<A id = "turnToContent" href = "# content"> </a> |
Then, set the content block with id as content at the position we want. Here, we use a div to simulate an article that is not similar to the article. It is best to place this div in the back position, so the effect is obvious. If you just test this effect, you can put a lot
Label.
?
| 1 2 3 4 5 6 7 8 9 |
<Div id = "content"> <H2> <A href = "###"> HTML5 </a> </H2> <P> Html5html5html5 </P> <P class = "addMes"> tag: <span> HTML5 </span> <small> August 1, April 19, 2015 </small> </p> </Div> |
The last step is to use JQuery to achieve smooth transition:
?
| 1 2 3 4 5 6 |
$ ('# Turntocontent'). click (function (){ $ ('Html, body'). animate ({ ScrollTop: $ ($. attr (this, 'href '). offset (). top },500 ); Return false; }); |
Done!
Next let's continue to improve,
?
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$ (Function (){ $ ('A [href * = #], area [href * = #] '). click (function (){ If (location. pathname. replace (/^ \/, '') = this. pathname. replace (/^ \ //, '') & location. hostname = this. hostname ){ Var $ target = $ (this. hash ); $ Target = $ target. length & $ target | $ ('[name =' + this. hash. slice (1) + ']'); If ($ target. length ){ Var targetOffset = $ target. offset (). top; $ ('Html, body'). animate ({ ScrollTop: targetOffset }, 1000 ); Return false; } } }); }) |
The advantage of the improved code is that you can click the anchor link to smoothly scroll to the anchor, and the URL Suffix of the browser does not contain the anchor. You do not need to modify the above Code in the process.
The above is all the content of this article. I hope you will like it.