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

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

有没有办法使滚动流畅?

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


当前回答

$('a[href*=#]').click(function(event){
    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
    event.preventDefault();
});

这对我来说是完美的

其他回答

正确的语法是:

//Smooth scrolling with links
$('a[href^=\\#]').on('click', function(event){     
    event.preventDefault();
    $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});

// Smooth scrolling when the document is loaded and ready
$(document).ready(function(){
  $('html,body').animate({scrollTop:$(location.hash).offset().‌​top}, 500);
});

简化:干

function smoothScrollingTo(target){
  $('html,body').animate({scrollTop:$(target).offset().​top}, 500);
}
$('a[href^=\\#]').on('click', function(event){     
    event.preventDefault();
    smoothScrollingTo(this.hash);
});
$(document).ready(function(){
  smoothScrollingTo(location.hash);
});

href^=\\#说明:

^表示它匹配包含# char的内容。因此,只匹配锚,以确保它是一个链接到同一页面(感谢Peter Wong的建议)。 \\是因为#在CSS选择器中是一个特殊字符,所以我们必须转义它。

添加:

function () {
    window.location.hash = href;
}

是否使垂直偏移量无效

top - 72

Firefox和IE浏览器,但Chrome浏览器没有。基本上,页面平滑地滚动到基于偏移量它应该停止的位置,但然后向下跳转到没有偏移量的页面所在的位置。

它确实将哈希添加到url的末尾,但按下back并不会让你回到顶部,它只是从url中删除哈希,并留下它所在的查看窗口。

这是我使用的完整js:

var $root = $('html, body');
$('a').click(function() {
    var href = $.attr(this, 'href');
    $root.animate({
        scrollTop: $(href).offset().top - 120
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});

使用JQuery:

$('a[href*=#]').click(function(){
  $('html, body').animate({
    scrollTop: $( $.attr(this, 'href') ).offset().top
  }, 500);
  return false;
});

此解决方案也适用于以下url,而不会破坏指向不同页面的锚点链接。

http://www.example.com/dir/index.html
http://www.example.com/dir/index.html#anchor

./index.html
./index.html#anchor

etc.

var $root = $('html, body');
$('a').on('click', function(event){
    var hash = this.hash;
    // Is the anchor on the same page?
    if (hash && this.href.slice(0, -hash.length-1) == location.href.slice(0, -location.hash.length-1)) {
        $root.animate({
            scrollTop: $(hash).offset().top
        }, 'normal', function() {
            location.hash = hash;
        });
        return false;
    }
});

我还没有在所有浏览器中测试这个功能。

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

$('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