简体   繁体   中英

jQuery scroll to anchor with variable speed

I have a very basic HTML site with a few anchor tags. On click each anchor leads to the other, using a little bit of smooth scroll with this function:

$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {  
        e.preventDefault(); var target = this.hash; var $target = $(target);
        $('html, body').stop().animate(
            {
                'scrollTop': $target.offset().top - 300
            },
            900,
            'swing',
            function () {
                window.location.hash = target - 300 ;
            }
        );
    });
});

The gaps between the anchors will be quite big and I am trying to figure out a way to get the speed to vary - when clicked on an anchor, to start slower, than speed up, when close to the next anchor to slow down again before it stops.

Could not find any JQuery docs on it, does someone has a suggestion?

FIDDLE: https://jsfiddle.net/koteva/ovf9ywb3/

I believe you would want to use an easing function to handle this. By default, jQuery only handles swing easing, which you have already passed into your animate function. However, you can include additional easing functions with a plugin.

George Smith has a lightweight js plugin for download that may help you, called jquery.easing.1.3.js . I think easeInOutQuart sounds like the closest thing to what you are looking for

Here is a demo fiddle

By including jQuery UI (after jQuery) you will be able to use the easings listed here

Your code should look like:

$('html, body').stop().animate(
    {
        'scrollTop': $target.offset().top - 300
    },
    900,
    'easeInOutCubic',
    function () {
        window.location.hash = target - 300 ;
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM