10

I have tried many different codes to smooth scroll to anchors. I can't find one that works. It needs to be able to scroll vertically, horizontally, and diagonally. Another problem I find with others is that they don't seem to work with multiple targets. I want it to be able to scroll to any anchor on the page without having to edit the script.

Fiddle

This is the code that matches this the closest, I cant get it to work:

var $root = $('html, body');
$('a').click(function () {

    $root.animate({

        scrollLeft: $($.attr(this, 'href')).offset().left,
        scrollTop: $($.attr(this, 'href')).offset().top

    }, 500);

    return false;
});

It works in JSFiddle but when I put it on my page it doesn't work.

Why is this not a duplicate? This is a multi-direction script that doesn't target single elements. It applies to all the links on the page.

4

1 回答 1

2

我无法让你的 jsfiddle 工作,看看这是否有效:

$(function(){
    $('a').on({
      click:function (e) {
        e.preventDefault();
        var root = $("html, body");
        var target = $(this).attr("href");
        root.animate({  
            scrollLeft: $(target).offset().left,
            scrollTop: $(target).offset().top
        }, 500);
      }
    });
)};
于 2013-08-13T17:47:50.823 回答