单击锚链接时平滑滚动 [英] Smooth scrolling when clicking an anchor link

查看:136
本文介绍了单击锚链接时平滑滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有几个超链接。用户在访问我的帮助部分时将阅读的常见问题解答。

I have a couple of hyperlinks on my page. A FAQ that users will read when they visit my help section.

使用锚点链接,我可以使页面滚动到锚点并引导用户在那里。

Using Anchor links, I can make the page scroll towards the anchor and guide the users there.

有没有办法让滚动顺畅?

Is there a way to make that scrolling smooth?

但请注意他正在使用自定义JavaScript库。也许jQuery提供了这样的东西?

But notice that he's using a custom JavaScript library. Maybe jQuery offers somethings like this baked in?

推荐答案

更新2018年4月:现在有以原生方式执行此操作

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

目前仅在最前沿的浏览器中支持。

This is currently only supported in the most bleeding edge browsers.

对于较旧的浏览器支持,您可以使用此jQuery技术:

For older browser support, you can use this jQuery technique:

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});

这里是小提琴: http://jsfiddle.net/9SDLw/

如果您的目标元素没有ID,你通过名称链接它,使用它:

If your target element does not have an ID, and you're linking to it by its name, use this:

$('a[href^="#"]').click(function () {
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
    }, 500);

    return false;
});






为了提高性能,你应该缓存 $('html,body')选择器,这样它就不会每次运行点击一个锚点:


For increased performance, you should cache that $('html, body') selector, so that it doesn't run every single time an anchor is clicked:

var $root = $('html, body');

$('a[href^="#"]').click(function () {
    $root.animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);

    return false;
});






如果您想更新网址,请执行它在 animate 回调中:

var $root = $('html, body');

$('a[href^="#"]').click(function() {
    var href = $.attr(this, 'href');

    $root.animate({
        scrollTop: $(href).offset().top
    }, 500, function () {
        window.location.hash = href;
    });

    return false;
});

这篇关于单击锚链接时平滑滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆