Scrolling to an Anchor using Transition/CSS3

前端 未结 10 901
-上瘾入骨i
-上瘾入骨i 2020-11-30 20:07

I have a series of links which are using an anchor mechanism:


      
10条回答
  •  情话喂你
    2020-11-30 21:02

    While some of the answers were very useful and informative, I thought I would write down the answer I came up with. The answer from Alex was very good, it is however limited in the sense that the height of the div needs to be hard coded in the CSS.

    So the solution I came up with uses JS (no jQuery) and is actually a stripped down version (almost to the minimum) of over solutions to solve similar problems I found on Statckoverflow:

    HTML

    
    
    blabla
    blabla
    blabla
    blabla

    NOTE THE "RETURN FALSE;" in the on click call. This is important if you want to avoid having your browser jumping to the link itself (and let the effect being managed by your JS).

    JS code:

    
    

    It's incredibly simple. It finds the vertical position of the div in the document using its unique ID (in the function test). Then it calls the scrollTo function passing the starting position (document.body.scrollTop) and the destination position (dest.offsetTop). It performs the transition using some sort of ease-inout curve.

    Thanks everyone for your help.

    Knowing a bit of coding can help you avoiding (sometimes heavy) libraries, and giving you (the programmer) more control.

提交回复
热议问题