Botão "Scroll to Top" - CSS, JavaScript
- Detalhes
- Angelo Luis Ferreira
- Botões
- Acessos: 12703
Script para criar um botão "Scroll to Top" para rolar uma página web até o topo com CSS e JavaScript.
HTML
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
CSS
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}
#myBtn {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 999;
font-size: 18px;
border: none;
outline: none;
background-color: green;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
#myBtn:hover {
background-color: #555;
JavaScript
// pegar botão
var mybutton = document.getElementById("myBtn");
// quando rolar a página 20px do topo para baixo, o botão será exibido
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// // quando clicar no botão, a página rola para o topo do documento
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
EXEMPLO COMPLETO
See the Pen ExNNoYW by Angelo Luis Ferreira (@angeloalf) on CodePen.
TENTE VOCÊ MESMO
Veja no nosso editor HTML como foi criado o botão "Scroll to Top". No editor, altere os códigos da forma que você desejar até conseguir o design desejado. Depois é só copiar os códigos e colar no seu projeto.
O anúncio abaixo ajuda manter o Portal Visual Dicas