Forum.scrollTop (); + animação

eu configuro a página para se deslocar para o topo quando um botão é carregado. Mas primeiro eu usei uma declaração if para ver se o topo da página não foi definido para 0. Então se não for 0 eu animarei a página para rolar para o topo.

var body = $("body");
var top = body.scrollTop() // Get position of the body

if(top!=0)
{
  body.animate({scrollTop:0}, '500');
}
A parte difícil agora é animar algo depois da Página ter passado para o topo. Então o meu próximo pensamento é, descobrir qual é a posição da página. Então usei o registo da consola para descobrir.

console.log(top);  // the result was 365
Isto deu-me um resultado de 365. o número de posição em que estava mesmo antes de ir para o topo.

a minha pergunta é como é que eu configuro a posição para ser 0, para que possa adicionar outra animação que corra uma vez que a página esteja a 0?

Obrigado!

Author: Juan Di Diego, 2013-05-10

11 answers

Para fazer isto, poderá definir uma função de resposta para o comando animar que será executada depois de a animação de posicionamento ter terminado.

Por exemplo:

var body = $("html, body");
body.stop().animate({scrollTop:0}, 500, 'swing', function() { 
   alert("Finished animating");
});

Onde está o código de alerta, você pode executar mais javascript para adicionar em animação posterior.

Além disso, o' swing ' está lá para facilitar. Confira http://api.jquery.com/animate / para mais informações.

 322
Author: TLS, 2017-05-04 07:18:43

Tenta este código:

$('.Classname').click(function(){
    $("html, body").animate({ scrollTop: 0 }, 600);
    return false;
});
 58
Author: Shailesh, 2014-08-29 13:49:09

Usa isto:

$('a[href^="#"]').on('click', function(event) {

    var target = $( $(this).attr('href') );

    if( target.length ) {
        event.preventDefault();
        $('html, body').animate({
            scrollTop: target.offset().top
        }, 500);
    }

});
 33
Author: Beep, 2015-02-17 21:42:34

Para isso, pode usar o método de callback

body.animate({
      scrollTop:0
    }, 500, 
    function(){} // callback method use this space how you like
);
 8
Author: The Mechanic, 2017-05-04 07:20:08

Tenta isto em vez disso:

var body = $("body, html");
var top = body.scrollTop() // Get position of the body
if(top!=0)
{
       body.animate({scrollTop :0}, 500,function(){
         //DO SOMETHING AFTER SCROLL ANIMATION COMPLETED
          alert('Hello');
      });
}
 7
Author: Kishan Patel, 2017-05-04 07:19:45

Solução simples:

Deslocar-se para qualquer elemento por ID ou nome:

SmoothScrollTo("#elementId", 1000);

Código:

function SmoothScrollTo(id_or_Name, timelength){
    var timelength = timelength || 1000;
    $('html, body').animate({
        scrollTop: $(id_or_Name).offset().top-70
    }, timelength, function(){
        window.location.hash = id_or_Name;
    });
}
 5
Author: T.Todua, 2018-11-30 17:44:49

Código com função click ()

    var body = $('html, body');

    $('.toTop').click(function(e){
        e.preventDefault();
        body.animate({scrollTop:0}, 500, 'swing');

}); 

.toTop = classe do elemento clicado talvez img ou a

 4
Author: Scorby, 2017-05-04 07:20:17
jQuery("html,body").animate({scrollTop: jQuery("#your-elemm-id-where you want to scroll").offset().top-<some-number>}, 500, 'swing', function() { 
       alert("Finished animating");
    });
 4
Author: Junaid, 2017-10-18 07:44:52

tens de ver isto.

$(function () {
        $('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;
                }
            }
        });
    });

Ou experimentá-los

$(function () {$('a').click(function () {
$('body,html').animate({
    scrollTop: 0
}, 600);
return false;});});
 0
Author: Remal Mahmud, 2018-03-27 09:01:57
$("body").stop().animate({
        scrollTop: 0
    }, 500, 'swing', function () {
        console.log(confirm('Like This'))
    }
);
 0
Author: Amanverma Lucky, 2019-12-31 08:25:04

Você pode usar tanto a classe CSS como o ID HTML, para mantê-la simétrica eu sempre uso a classe CSS por exemplo

<a class="btn btn-full js--scroll-to-plans" href="#">I’m hungry</a> 
|
|
|
<section class="section-plans js--section-plans clearfix">

$(document).ready(function () {
    $('.js--scroll-to-plans').click(function () {
        $('body,html').animate({
            scrollTop: $('.js--section-plans').offset().top
        }, 1000);
        return false;})
});
 0
Author: Lord, 2020-06-30 13:41:44