我的页面上有几个超链接。一个常见问题,用户将阅读时,他们访问我的帮助部分。

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

有没有办法使滚动流畅?

但请注意,他使用的是自定义JavaScript库。也许jQuery提供了这样的功能?


当前回答

我很惊讶没有人发布一个本地解决方案,也负责更新浏览器位置哈希匹配。下面就是:

let anchorlinks = document.querySelectorAll('a[href^="#"]')
 
for (let item of anchorlinks) { // relitere 
    item.addEventListener('click', (e)=> {
        let hashval = item.getAttribute('href')
        let target = document.querySelector(hashval)
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })
        history.pushState(null, null, hashval)
        e.preventDefault()
    })
}

参见教程:http://www.javascriptkit.com/javatutors/scrolling-html-bookmark-javascript.shtml

对于带有粘头的站点,可以使用滚动填充顶部CSS来提供偏移量。

其他回答

2018年4月更新:现在有一种本地的方法来做到这一点:

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

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

目前只有最先进的浏览器支持这一功能。


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

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

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

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


如果你的目标元素没有ID,你通过它的名字链接到它,使用这个:

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

    return false;
});

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

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

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

    return false;
});

如果你想要更新URL,在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;
});

现在的浏览器要快一些。setInterval可能有用。现在这个功能在Chrome和Firefox中运行良好。(safari有点慢,不用IE)

function smoothScroll(event) {
    if (event.target.hash !== '') { //Check if tag is an anchor
        event.preventDefault()
        const hash = event.target.hash.replace("#", "")
        const link = document.getElementsByName(hash) 
        //Find the where you want to scroll
        const position = link[0].getBoundingClientRect().y 
        let top = 0

        let smooth = setInterval(() => {
            let leftover = position - top
            if (top === position) {
                clearInterval(smooth)
            }

            else if(position > top && leftover < 10) {
                top += leftover
                window.scrollTo(0, top)
            }

            else if(position > (top - 10)) {
                top += 10
                window.scrollTo(0, top)
            }

        }, 6)//6 milliseconds is the faster chrome runs setInterval
    }
}

我建议你编写这样的泛型代码:

$('a[href^="#"]').click(function(){

var the_id = $(this).attr("href");

    $('html, body').animate({
        scrollTop:$(the_id).offset().top
    }, 'slow');

return false;});

您可以在这里看到一篇非常好的文章:jquery- effect -smooth-scroll- pollution -fluide

如果你在页面上有一个简单的按钮可以向下滚动到一个div,并且希望返回按钮通过跳到顶部来工作,只需添加以下代码:

$(window).on('hashchange', function(event) {
    if (event.target.location.hash=="") {
        window.scrollTo(0,0);
    }
});

这也可以扩展到跳转到不同的div,通过读取哈希值,并像Joseph Silbers的答案一样滚动。

我对"/xxxxx#asdf"和"#asdf" href锚都这样做了

$("a[href*=#]").on('click', function(event){
    var href = $(this).attr("href");
    if ( /(#.*)/.test(href) ){
      var hash = href.match(/(#.*)/)[0];
      var path = href.match(/([^#]*)/)[0];

      if (window.location.pathname == path || path.length == 0){
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 1000);
        window.location.hash = hash;
      }
    }
});