简体   繁体   中英

Why scroll doesn't work correct?

Link to jsfiddle - https://jsfiddle.net/dn5t2mwm/3/

$('a.item_link').click(function(){
    var hash = this.hash, top = $(hash).offset().top;
    console.log(hash, top);
    $('html, body').animate({
        scrollTop: top
    }, 500);
    return false;
});

I want to make smooth scroll. But when i account coordinates of link with anchor it returns different results. It looks like it accounts coordinates from the start of viewport - not a start of document. It works on codepen, but doesn't work on local and jsfiddle. css is disabled. Maybe you know what is wrong with it?

Use this piece of code:

$('a[href*="#"]:not([href="#"])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);
            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