简体   繁体   English

jQuery滚动以可变速度锚定

[英]jQuery scroll to anchor with variable speed

I have a very basic HTML site with a few anchor tags. 我有一个非常基本的HTML网站,上面有一些锚标签。 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? 找不到关于它的任何JQuery文档,有人提出建议吗?

FIDDLE: https://jsfiddle.net/koteva/ovf9ywb3/ 内容: 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. 默认情况下,jQuery仅处理swing缓动,您已将其传递给animate函数。 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 . George Smith有一个可供下载的轻量级js插件,名为jquery.easing.1.3.js ,可以为您提供帮助。 I think easeInOutQuart sounds like the closest thing to what you are looking for 我认为easeInOutQuart听起来像是您要寻找的最接近的东西

Here is a demo fiddle 这是一个演示小提琴

By including jQuery UI (after jQuery) you will be able to use the easings listed here 通过包括jQuery UI (在jQuery之后),您将可以使用此处列出的缓动

Your code should look like: 您的代码应如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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