Domanda

I use the below code to make auto scrolling to anchor

        setTimeout(function(){window.location.hash = "#anchor";},5000);

It's working fine, but I need to add a smooth effect when it scroll.

JSFIDDLE

È stato utile?

Soluzione

A common solution using jQuery is to animate the scrollTop property to the offset y-position of the target element:

$('html,body').animate({
    scrollTop: $('#anchor').offset().top
});

Demo: http://jsfiddle.net/HZejZ/1/

You might be able to listen to the hashchange event if you want to keep your code as it is (untested):

$(window).on('hashchange', function(e) {
    e.preventDefault();
    var $target = $(window.location.hash);
    if ( $target.length ) {
        $('html,body').animate({scrollTop: $target.offset().top});
    }
});

(edit: this seems to be problematic, the browser will jump even if preventDefault is called)

Altri suggerimenti

Use below code

  $('html, #anchor').animate({ scrollTop: 0 },'slow');

It is 100% working code. If it is also working for you then please mark it as an answer so that others can also use it...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top