简体   繁体   中英

Smooth scrolling doesn't work with a . in ID

I am using a script for smooth scrolling from here Smooth scrolling when clicking an anchor link (the version where the URL is changed).

It works for all anchors except those that have a . in their ID. So linking to:

  • 1 works

  • 1.1 doesn't work

Any idea of how to fix this?

Code:

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

Demo: http://bagsy.netau.net/rj/rj.html

The id should not start with a digit. But if you don't want to change id, you can use this code:

var $root = $('html, body'); 
$('a').click(function() {
    var href = $.attr(this, 'href').replace('#','');
    $root.animate({
        scrollTop: $('[id="'+href +'"]').offset().top
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM