CSS3 Transitions with Anchors

半世苍凉 提交于 2019-12-04 19:10:43
Giona

I don't think you can do it with just CSS. Here's a function to achieve it with jQuery:

$('a[href^=#]').on("click",function(e){
    var t= $(this.hash);
    var t=t.length&&t||$('[name='+this.hash.slice(1)+']');
    if(t.length){
        var tOffset=t.offset().top;
        $('html,body').animate({scrollTop:tOffset-20},'slow');
        e.preventDefault();
    }
});​

This will work with any <a href="#any-id-or-name"> anchor. Demo.

To make it scroll faster or slower, change 'slow' to 'fast' or any numeric value in milliseconds.

You can scroll to any element of a page with the scrollIntoView JavaScript method. It is available on any element. document.getElementById("yourElement").scrollIntoView(); will scroll to yourElement. With Firefox, you can even scroll smoothly by adding {behavior:'smooth'} as a param of the method. This is not cross-browser unfortunately.

If you want a cross-browser VanillaJS lib, I would recommend Smooth-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!