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

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

有没有办法使滚动流畅?

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


当前回答

不需要任何js只是使用滚动行为:平滑的html标签就是这样

html{
scroll-behavior: smooth;
}

其他回答

要求jquery和动画锚标签与指定的名称而不是id,同时添加哈希到浏览器url。还修复了大多数jquery答案中#符号没有带转义反斜杠前缀的错误。返回按钮,不幸的是,不能正确地导航回以前的哈希链接…

$('a[href*=\\#]').click(function (event)
{
    let hashValue = $(this).attr('href');
    let name = hashValue.substring(1);
    let target = $('[name="' + name + '"]');
    $('html, body').animate({ scrollTop: target.offset().top }, 500);
    event.preventDefault();
    history.pushState(null, null, hashValue);
});

这里已经有很多很好的答案——但是他们都忽略了一个事实,即空锚必须被排除在外。否则,只要单击空锚,这些脚本就会生成JavaScript错误。

在我看来,正确答案是这样的:

$('a[href*=\\#]:not([href$=\\#])').click(function() {
    event.preventDefault();

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

不要忘记offset()函数将元素的位置传递给文档。所以当你需要滚动你的元素相对于它的父元素时你应该使用这个;

    $('.a-parent-div').find('a').click(function(event){
        event.preventDefault();
        $('.scroll-div').animate({
     scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
     }, 500);       
  });

关键点是获得scroll-div的scrollTop,并将其添加到scrollTop。如果你不这样做,position()函数总是会给你不同的位置值。

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

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来提供偏移量。

只有CSS

html {
    scroll-behavior: smooth;
}

你只需要加上这个。现在你的内部链接滚动行为将是流畅的像一个流。

程序化:一些额外的和高级的东西

// Scroll to specific values
// window.scrollTo or window.scroll
window.scroll({
  top: 1000, 
  left: 0, 
  behavior: 'smooth'
});

// Scroll certain amounts from current position 
window.scrollBy({ 
  top: 250, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});

// Scroll to a certain element
document.getElementById('el').scrollIntoView({
  behavior: 'smooth'
})

注意:所有最新的浏览器(Opera, Chrome, Firefox等)都支持此功能。

要详细了解,请阅读这篇文章