Así que antes escribí un pequeño fragmento de código para implementar un desplazamiento suave en mi página web. Inicialmente funcionaba bien, pero a medida que avanzaba el desarrollo, dejó de funcionar aleatoriamente y no ha vuelto a funcionar desde entonces. Ahora, cuando se desplaza, hay un retraso desde que presiona el botón y luego, finalmente, se ajusta a la parte de la página a la que se dirige.
Aquí está la etiqueta del script para la biblioteca:
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/smooth-scroll@15.0.0/dist/smooth-scroll.polyfills.min.js"></script>Y aquí está el javascript:
const scroll = new SmoothScroll('nav a[href*="#"]',{ speed: 800 }); No quiero usar el scroll-behavior: smooth porque la mayoría del tráfico de mis sitios estará en Safari, que no lo admite.
Para los navegadores que no admiten la propiedad de comportamiento de desplazamiento, puede usar JavaScript o una biblioteca de JavaScript, como jQuery, para crear una solución que funcione para todos los navegadores:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ // Add smooth scrolling to all links $("a").on('click', function(event) { // Make sure this.hash has a value before overriding default behavior if (this.hash !== "") { // Prevent default anchor click behavior event.preventDefault(); // Store hash var hash = this.hash; // Using jQuery's animate() method to add smooth page scroll // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area $('html, body').animate({ scrollTop: $(hash).offset().top }, 800, function(){ // Add hash (#) to URL when done scrolling (default click behavior) window.location.hash = hash; }); } // End if }); }); </script>