Existe uma maneira de rolar para baixo para um link de âncora usando jQuery?
Gostar:
$(document).ready(function(){ $("#gotomyanchor").click(function(){ $.scrollSmoothTo($("#myanchor")); }); });
?
Aqui está como eu faço:
var hashTagActive = ""; $(".scroll").on("click touchstart" , function (event) { if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll. event.preventDefault(); //calculate destination place var dest = 0; if ($(this.hash).offset().top > $(document).height() - $(window).height()) { dest = $(document).height() - $(window).height(); } else { dest = $(this.hash).offset().top; } //go to destination $('html,body').animate({ scrollTop: dest }, 2000, 'swing'); hashTagActive = this.hash; } });
Então você só precisa criar sua âncora assim:
Destination 1
Você pode ver no meu site .
Uma demonstração também está disponível aqui: http://jsfiddle.net/YtJcL/
Eu usaria o trecho de código simples do CSS-Tricks.com:
$(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; } } }); });
Fonte : http://css-tricks.com/snippets/jquery/smooth-scrolling/
A melhor solução que já vi até agora: jQuery: Links de Âncora Internos de Rolagem Suave
HTML:
Scroll to comments
Roteiro:
jQuery(document).ready(function($) { $(".scroll").click(function(event){ event.preventDefault(); $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500); }); });
jQuery.scrollTo fará tudo o que quiser e muito mais!
Você pode passar todos os tipos de coisas diferentes:
Aqui está o código que usei para vincular rapidamente o scrollTo do jQuery a todos os links de âncora:
// Smooth scroll $('a[href*=#]').click(function () { var hash = $(this).attr('href'); hash = hash.slice(hash.indexOf('#') + 1); $.scrollTo(hash == 'top' ? 0 : 'a[name='+hash+']', 500); window.location.hash = '#' + hash; return false; });
Tente este. É um código de truques CSS que eu modifiquei, é bastante simples e faz tanto a rolagem horizontal e vertical. Precisa de JQuery. Aqui está uma demonstração
$(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-10, scrollLeft:target.offset().left-10 }, 1000); return false; } } }); });
Usando o script do hanoo, criei uma function jQuery:
$.fn.scrollIntoView = function(duration, easing) { var dest = 0; if (this.offset().top > $(document).height() - $(window).height()) { dest = $(document).height() - $(window).height(); } else { dest = this.offset().top; } $('html,body').animate({ scrollTop: dest }, duration, easing); return this; };
uso:
$('#myelement').scrollIntoView();
Os padrões para duração e atenuação são 400ms e “swing”.
Eu usei no meu site isso:
$(document).ready(function(){ $('a[href^="#"]').on('click',function (e) { e.preventDefault(); var target = this.hash, $target = $(target); $('html, body').stop().animate({ 'scrollTop': $target.offset().top }, 1200, 'swing', function () { window.location.hash = target; }); });
});
Você pode alterar a velocidade da rolagem alterando o “1200” i usado por padrão, ele funciona razoavelmente bem na maioria dos navegadores.
depois de colocar o código entre a tag
da sua página, você precisará criar o link interno na sua tag :
Go to Home
Espero que ajude!
Ps: Não se esqueça de ligar:
Eu usei o plugin Smooth Scroll , em http://plugins.jquery.com/smooth-scroll/ . Com este plugin, tudo o que você precisa include é um link para o jQuery e para o código do plugin:
(os links precisam ter a class smoothScroll
para funcionar).
Outro recurso do Scroll Suave é que o nome antigo não é exibido na URL!
trabalho
$('a[href*=#]').each(function () { $(this).attr('href', $(this).attr('href').replace('#', '#_')); $(this).on( "click", function() { var hashname = $(this).attr('href').replace('#_', ''); if($(this).attr('href') == "#_") { $('html, body').animate({ scrollTop: 0 }, 300); } else { var target = $('a[name="' + hashname + '"], #' + hashname), targetOffset = target.offset().top; if(targetOffset >= 1) { $('html, body').animate({ scrollTop: targetOffset-60 }, 300); } } }); });
Eu odeio adicionar classs com nomes de function ao meu código, então eu coloco isso junto em vez disso. Se eu parasse de usar a rolagem suave, eu me sentiria à vontade para passar pelo meu código e excluir todas as coisas da class “rolagem”. Usando essa técnica, posso comentar 5 linhas de JS, e todo o site é atualizado. 🙂
Smooth Smooth ... ... ...
Requisitos :
1. elementos devem ter um atributo href que comece com
#
e seja mais do que apenas #
2. Um elemento na página com um atributo id
correspondente
O que faz:
1. A function usa o valor href para criar o object anchorID
– No exemplo, é $('#contact')
, https://stackoverflow.com/about
começa com /
2. HTML
e BODY
são animados para o deslocamento superior do anchorID
– velocidade = ‘normal’ (‘rápido’, ‘lento’, milissegundos,)
– easing = ‘swing’ (‘linear’, etc … google easing)
3. return false
– evita que o navegador mostre o hash no URL
– o script funciona sem ele, mas não é tão ” suave “.