Para implementar rolagem suave (smooth scroll) em seu site, existem várias abordagens. Aqui estão as principais:
Adicione a propriedade scroll-behavior
ao elemento raiz do seu CSS:
html {
scroll-behavior: smooth;
}
Funciona para:
<a href="#section">
)window.scrollTo()
)Compatibilidade:
Funciona na maioria dos navegadores modernos (Chrome, Firefox, Edge), mas
não no IE ou Safari antigo.
Para mais controle ou compatibilidade, use métodos JavaScript:
scrollTo()
// Rolagem suave para coordenadas específicas
window.scrollTo({
top: 1000,
behavior: 'smooth'
});
// Ou para um elemento
const element = document.getElementById('section');
element.scrollIntoView({ behavior: 'smooth' });
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
target.scrollIntoView({ behavior: 'smooth' });
});
});
Para controlar duração ou efeitos de easing:
function smoothScrollTo(target, duration = 1000) {
const start = window.pageYOffset;
const distance = target.offsetTop - start;
let startTime = null;
function animation(currentTime) {
if (!startTime) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const progress = Math.min(timeElapsed / duration, 1);
window.scrollTo(0, start + distance * easeInOutQuad(progress));
if (timeElapsed < duration) {
requestAnimationFrame(animation);
}
}
function easeInOutQuad(t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
}
requestAnimationFrame(animation);
}
// Uso:
smoothScrollTo(document.getElementById('secao'), 1500);
SmoothScroll.js (leve: ~4KB):
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/smooth-scroll/dist/smooth-scroll.polyfills.min.js"></script>
<script>
const scroll = new SmoothScroll('a[href*="#"]');
</script>
jQuery (se já estiver usando):
$('a[href^="#"]').on('click', function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $($(this).attr('href')).offset().top
}, 500);
});
smoothscroll-polyfill
) se precisar de
suporte para Safari ou IE.element.focus()
após a
rolagem.