Tengo esta aplicación que al bajar 500 px, aparece un botón de desplazamiento hacia arriba y al volver a subir, desaparece. Pero el efecto es rápido y no tiene animación:
JS
const ScrollTop = () => { const [visible, setVisible] = useState(false); // Show Button After Scrolling Down More than 500px const toggleVisible = () => { if ( document.body.scrollTop > 500 || document.documentElement.scrollTop > 500 ) { setVisible(true); } else { setVisible(false); } }; // Listen for Scrolling Event window.addEventListener("scroll", toggleVisible); // Get Back Top when Clicked const handleScroll = () => { window.scrollTo({ top: 0, }); }; return ( <button id="back-to-top" style={{ display: visible ? "block" : "none" }} onClick={handleScroll} title="Go To Top" > <i className="fas fa-chevron-circle-up"></i> </button> ); };CSS
#back-to-top { background: none; background-repeat: no-repeat; border: none; cursor: pointer; overflow: hidden; outline: none; position: fixed; bottom: 30px; right: 20px; color: rgb(255, 51, 0); z-index: 99; font-size: 2.5rem; } #back-to-top:hover { color: rgb(255, 0, 140); }¿Hay alguna forma en CSS y JS de agregar un efecto de transición a su comportamiento para que aparezca y desaparezca suavemente?
Para el estilo, sugiero aplicar condicionalmente un nombre de clase cuando desee mostrar el botón de volver a arriba. También querrá mover la adición ( y eliminación ) del detector de desplazamiento de la ventana a un gancho useEffect . El useEffect debe agregar el detector de eventos y devolver una función de limpieza para eliminarlo cuando se desmonte el componente ScrollTop . Proporcione false como tercer argumento para que use oyentes pasivos.
const ScrollTop = () => { const [visible, setVisible] = useState(false); // Show Button After Scrolling Down More than 500px const toggleVisible = () => { if ( document.body.scrollTop > 500 || document.documentElement.scrollTop > 500 ) { setVisible(true); } else { setVisible(false); } }; useEffect(() => { // Listen for Scrolling Event window.addEventListener("scroll", toggleVisible, false); return () => { window.removeEventListener("scroll", toggleVisible, false); } }, []); // Get Back Top when Clicked const handleScroll = () => { window.scrollTo({ top: 0, }); }; return ( <button id="back-to-top" className={visible ? "back-to-top-visible" : null} onClick={handleScroll} title="Go To Top" > <i className="fas fa-chevron-circle-up"></i> </button> ); }; CSS: cómo desea realizar la transición depende de usted, pero el punto de partida básico es definir una regla de transition con propiedades para la transición, una duración, función de aceleración/tiempo y retraso. Para el ejemplo, elegí hacer la transición de la escala. Comience con un valor de escala inicial de 0, y cuando se aplique el nombre de clase back-to-top-visible finalice con un valor de escala de 1.
#back-to-top { background: none; background-repeat: no-repeat; border: none; cursor: pointer; overflow: hidden; outline: none; position: fixed; bottom: 30px; right: 20px; color: rgb(255, 51, 0); z-index: 99; font-size: 2.5rem; transform: scale(0); transition: all 0.5s ease-in-out; } #back-to-top:hover { color: rgb(255, 0, 140); } #back-to-top.back-to-top-visible { transform: scale(1); }Todo lo que necesita es apuntar al botón en su CSS y agregar una transición como esta:
#back-to-top { transition: all 0.2s linear; }o puede probar esta solución donde puede representar la clase condicionalmente.
CSS:
#back-to-top { background: none; background-repeat: no-repeat; border: none; cursor: pointer; overflow: hidden; outline: none; position: fixed; bottom: 30px; right: 20px; color: rgb(255, 51, 0); z-index: 99; font-size: 2.5rem; transition: all 0.6s linear; } .hide-class { opacity: 0; z-index: -100; } .show-class { opacity: 1; } #back-to-top:hover { color: rgb(255, 0, 140); } import React, {useState} from "react"; import "./style.css";Desplazamiento superior:
const App = () => { const [visible, setVisible] = useState(false); // Show Button After Scrolling Down More than 500px const toggleVisible = () => { if ( document.body.scrollTop > 500 || document.documentElement.scrollTop > 500 ) { setVisible(true); } else { setVisible(false); } }; // Listen for Scrolling Event window.addEventListener("scroll", toggleVisible); // Get Back Top when Clicked const handleScroll = () => { window.scrollTo({ top: 0, }); }; return ( <React.Fragment> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <p>Content</p><p>Content</p> <button id="back-to-top" className={`${visible ? 'show-class': 'hide-class'}`} onClick={handleScroll} title="Go To Top" > Go to top </button> </React.Fragment> ); }; export default App;