Desplazamiento suave al hacer clic en un enlace de anclaje

Tengo un par de hipervínculos en mi página. Preguntas frecuentes que los usuarios leerán cuando visiten mi sección de ayuda.

Usando enlaces de ancla, puedo hacer que la página se desplace hacia el ancla y guíe a los usuarios allí.

¿Hay alguna forma de suavizar el desplazamiento?

Pero observe que está usando una biblioteca JavaScript personalizada. ¿Quizás jQuery ofrece algunas cosas como esta incorporadas?

preguntado Oct 10 '11, 16:10

¿Puede revisar la mejor respuesta tal vez? La solución pura de CSS de una línea es difícil de encontrar entre todas las sugerencias voluminosas de jquery: stackoverflow.com/a/51588820/1422553 -

28 Respuestas

Actualizar abril 2018: Hay ahora una forma nativa de hacer esto:

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

Actualmente, esto solo es compatible con los navegadores más avanzados.


Para compatibilidad con navegadores más antiguos, puede utilizar esta técnica de jQuery:

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});

Y aquí está el violín: http://jsfiddle.net/9SDLw/


Si su elemento de destino no tiene un ID y lo está vinculando por su name, utilizar este:

$('a[href^="#"]').click(function () {
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
    }, 500);

    return false;
});

Para un mayor rendimiento, debe almacenar en caché $('html, body') selector, para que no se ejecute cada vez se hace clic en un ancla:

var $root = $('html, body');

$('a[href^="#"]').click(function () {
    $root.animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);

    return false;
});

Si desea que se actualice la URL, hágalo dentro del animate llamar de vuelta:

var $root = $('html, body');

$('a[href^="#"]').click(function() {
    var href = $.attr(this, 'href');

    $root.animate({
        scrollTop: $(href).offset().top
    }, 500, function () {
        window.location.hash = href;
    });

    return false;
});

Respondido 08 Abr '18, 16:04

Esto parece eliminar la #extensión de la URL, rompiendo la función de retroceso. ¿Hay alguna forma de evitar esto? - Fletch

@JosephSilber ¿no debería ser así? scrollTop: $(this.hash).offset().top en lugar de scrollTop: $(this.href).offset().top? - Gregorio Pakosz

@CreateSean - scrollTop: $(href).offset().top - 72 - José Silber

Yo diría que almacenar en caché el html, body el objeto aquí es innecesario, ejecutar un selector una vez por clic no es realmente tanto. - usuario3638471

La primera solución es la mejor y la más moderna, puede usar este polyfill para admitir este comportamiento en navegadores antiguos con esto polyfill - Efe

La sintaxis correcta es:

//Smooth scrolling with links
$('a[href*=\\#]').on('click', function(event){     
    event.preventDefault();
    $('html,body').animate({scrollTop:$(this.hash).offset().top}, 500);
});

// Smooth scrolling when the document is loaded and ready
$(document).ready(function(){
  $('html,body').animate({scrollTop:$(location.hash).offset().‌​top}, 500);
});

Simplificación: SECO

function smoothScrollingTo(target){
  $('html,body').animate({scrollTop:$(target).offset().​top}, 500);
}
$('a[href*=\\#]').on('click', function(event){     
    event.preventDefault();
    smoothScrollingTo(this.hash);
});
$(document).ready(function(){
  smoothScrollingTo(location.hash);
});

Explicación de href*=\\#:

  • * significa que coincide con lo que contiene # carbonizarse. Por lo tanto, solo coincide anclas. Para obtener más información sobre el significado de esto, consulte aquí
  • \\ es porque el # es un carácter especial en el selector css, por lo que tenemos que escapar de él.

Respondido el 25 de junio de 19 a las 17:06

tuve que cambiar $('a') a $('a[href*=#]') para servir solo URL de anclaje - okliv

@okliv Esto servirá demasiado, por ejemplo, un enlace javascript como <a href="javascript:$('#test').css('background-color', '#000')">Test</a>. Deberías usar $('a[href^=#]') para hacer coincidir todas las URL que comienzan con un carácter hash. - Martin Braun

Además, '#' es un carácter especial y debe escaparse así: a[href^=\\#] - quinnfreedman

Esto provocó que los enlaces a los anclajes en otras páginas dejaran de funcionar. Resuelto agregando un if ($ ($ (this.hash) .selector) .length) {... desplazamiento suave. } - liren

¿Cómo puedo animar esto cuando viajo por primera vez a una nueva página? Por ejemplo, haciendo clic en: sitio web.com/newpage/#section2. Me gustaría que cargara la página y luego se desplazara hacia abajo. ¿Es eso posible? - samyer

El nuevo picor en CSS3. Esto es mucho más fácil que todos los métodos enumerados en esta página y no requiere Javascript. Simplemente ingrese el código a continuación en su css y, de repente, los enlaces que apuntan a ubicaciones dentro de su propia página tendrán una animación de desplazamiento suave.

html{scroll-behavior:smooth}

Después de eso, cualquier enlace que apunte hacia un div se deslizará suavemente hacia esas secciones.

<a href="#section">Section1</a>

Editar: Para aquellos confundidos acerca de lo anterior, una etiqueta. Básicamente es un enlace en el que se puede hacer clic. Luego puede tener otra etiqueta div en algún lugar de su página web como

<div id="section">content</div>

En este sentido, se podrá hacer clic en el enlace a e irá a cualquier # sección, en este caso es nuestro div que llamamos sección.

Por cierto, pasé horas tratando de que esto funcionara. Encontré la solución en alguna sección de comentarios oscuros. Tenía errores y no funcionaría en algunas etiquetas. No funcionó en el cuerpo. Finalmente funcionó cuando lo puse en html {} en el archivo CSS.

Respondido 27 Jul 21, 03:07

Puedo ser muy útil pero ellos son inconvenientes - Buzut

bueno, pero ten cuidado porque de momento no es compatible con Safari y obviamente con Explorer (03/2019) - marco romano

buena solución, solo la cobertura es con 74,8% limitada. quizás en el futuro - Mario

Que increible. Muchas gracias. - mikkel fennefoss

Esta será la respuesta más relevante en los próximos años. - nurul huda

Solo CSS

html {
    scroll-behavior: smooth !important;
}

Todo lo que necesita para agregar solo esto. Ahora su comportamiento de desplazamiento de enlaces internos será suave como un flujo de corriente.

Programáticamente: algo extra y avanzado

// Scroll to specific values
// window.scrollTo or
window.scroll({
  top: 1000, 
  left: 0, 
  behavior: 'smooth'
});

// Scroll certain amounts from current position 
window.scrollBy({ 
  top: 250, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});

// Scroll to a certain element
document.getElementById('el').scrollIntoView({
  behavior: 'smooth'
})

Nota:: Todos los navegadores más recientes (Opera, Chrome, Firefox etc) admite esta función.

para una comprensión detallada, lea esto artículo

respondido 18 mar '21, 16:03

¡bonito! ¿Por qué esta no es la respuesta aceptada? ¡no necesitamos todo ese javascript! - Trevor de Koekkoek

Funciona muy bien, esta debería ser la respuesta aceptada. - tumba

Verifique el soporte del navegador aquí - ryan zhou

¡Esta es la mejor solución para un desplazamiento suave NUNCA! ¡Gracias! - Yehanny

Esa es la mejor respuesta en absoluto. Muchas gracias WasiF - sudar

$('a[href*=#]').click(function(event){
    $('html, body').animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);
    event.preventDefault();
});

esto funcionó perfecto para mí

respondido 11 mar '14, 12:03

"event.preventDefault ();" puede reemplazar "devolver falso"; - Andrés Separ

Lamento decirlo, pero no funciona y se muestra en la página llamada ancla rápidamente sin suavidad. - kamlesh

Me sorprende que nadie haya publicado una solución nativa que también se encargue de actualizar el hash de ubicación del navegador para que coincida. Aquí está:

let anchorlinks = document.querySelectorAll('a[href^="#"]')
 
for (let item of anchorlinks) { // relitere 
    item.addEventListener('click', (e)=> {
        let hashval = item.getAttribute('href')
        let target = document.querySelector(hashval)
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })
        history.pushState(null, null, hashval)
        e.preventDefault()
    })
}

Ver tutorial: http://www.javascriptkit.com/javatutors/scrolling-html-bookmark-javascript.shtml

Para sitios con encabezados fijos, scroll-padding-top CSS se puede utilizar para proporcionar un desplazamiento.

Respondido 29 Abr '20, 12:04

Me gusta más esta respuesta. Sin embargo, afais no hay forma de proporcionar una compensación. Como sería necesario en el caso de un encabezado fijo. - bskool

Desafortunadamente, el mismo soporte deficiente que para la propiedad de comportamiento de desplazamiento de CSS: desarrollador.mozilla.org/en-US/docs/Web/CSS/… - Dmitri Nevzorov

Me encanta, funciona fuera de la caja con historia y todo :) - avocada

Te sugiero que hagas este código genérico:

$('a[href^="#"]').click(function(){

var the_id = $(this).attr("href");

    $('html, body').animate({
        scrollTop:$(the_id).offset().top
    }, 'slow');

return false;});

Puedes ver un muy buen artículo aquí: jquery-effet-suave-scroll-profilement-fluide

Respondido 18 Feb 16, 15:02

Esto no es genérico, es jQuery. - AnrDaemon

$(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;
      }
    }
  });
});

Oficial: http://css-tricks.com/snippets/jquery/smooth-scrolling/

Respondido 15 ago 15, 02:08

esto solo parece funcionar para los enlaces de anclaje de la página interna, pero los enlaces de ancla de otras páginas no funcionan, por ejemplo website.com/about-us/#quienes-somos - lluviabrunotte

Ya hay muchas buenas respuestas aquí; sin embargo, a todas les falta el hecho de que las anclas vacías deben ser excluidas. De lo contrario, esos scripts generan errores de JavaScript tan pronto como se hace clic en un ancla vacía.

En mi opinión, la respuesta correcta es así:

$('a[href*=\\#]:not([href$=\\#])').click(function() {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});

Respondido 09 Oct 18, 22:10

Además, debe tener en cuenta cuando hace clic en un enlace hash de una URL diferente, por lo que habrá muchos window.location.... y $(this).attr('href').substring(...) manejando a lo largo - user151496

Usando JQuery:

$('a[href*=#]').click(function(){
  $('html, body').animate({
    scrollTop: $( $.attr(this, 'href') ).offset().top
  }, 500);
  return false;
});

respondido 23 nov., 15:20

Hay una forma CSS de hacer esto usando scroll-behavior. Agregue la siguiente propiedad.

    scroll-behavior: smooth;

Y eso es todo. No se requiere JS.

a {
  display: inline-block;
  width: 50px;
  text-decoration: none;
}
nav, scroll-container {
  display: block;
  margin: 0 auto;
  text-align: center;
}
nav {
  width: 339px;
  padding: 5px;
  border: 1px solid black;
}
scroll-container {
  display: block;
  width: 350px;
  height: 200px;
  overflow-y: scroll;
  scroll-behavior: smooth;
}
scroll-page {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 5em;
}
<nav>
  <a href="#page-1">1</a>
  <a href="#page-2">2</a>
  <a href="#page-3">3</a>
</nav>
<scroll-container>
  <scroll-page id="page-1">1</scroll-page>
  <scroll-page id="page-2">2</scroll-page>
  <scroll-page id="page-3">3</scroll-page>
</scroll-container>

PD: compruebe la compatibilidad del navegador.

Respondido 24 ago 18, 13:08

en qué contenedor debo usar el comportamiento de desplazamiento: suave; - locodroide

En caso de duda, agréguelo a la etiqueta del cuerpo @CraZyDroiD - Santosh

Hay soporte nativo para un desplazamiento suave en los pergaminos de id hash.

html {
  scroll-behavior: smooth;
}

Puedes echar un vistazo: https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2

Respondido el 08 de enero de 20 a las 12:01

La respuesta dada funciona pero deshabilita los enlaces salientes. A continuación, una versión con un bono adicional facilita la salida (swing) y respeta los enlaces salientes.

$(document).ready(function () {
    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});

Respondido 24 Abr '17, 19:04

+1 para el stop() sin embargo, la migaja de la URL no funciona como se esperaba: el botón Atrás no vuelve a aparecer, esto se debe a que cuando la migaja se establece en la URL después de que se completa la animación. Es mejor sin una migaja en la URL, por ejemplo, así es como funciona Airbnb. - Eric

HTML

<a href="#target" class="smooth-scroll">
    Link
</a>
<div id="target"></div>

o con URL completa absoluta

<a href="https://somewebsite.com/#target" class="smooth-scroll">
    Link
</a>
<div id="target"></div>

jQuery

$j(function() {
    $j('a.smooth-scroll').click(function() {
        if (
                window.location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
            &&  window.location.hostname == this.hostname
        ) {
            var target = $j(this.hash);
            target = target.length ? target : $j('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $j('html,body').animate({
                    scrollTop: target.offset().top - 70
                }, 1000);
                return false;
            }
        }
    });
});

Respondido el 30 de Septiembre de 17 a las 23:09

Los navegadores modernos son un poco más rápidos en estos días. Un setInterval podría funcionar. Esta función funciona bien en Chrome y Firefox en estos días (un poco lento en safari, no se molestó con IE)

function smoothScroll(event) {
    if (event.target.hash !== '') { //Check if tag is an anchor
        event.preventDefault()
        const hash = event.target.hash.replace("#", "")
        const link = document.getElementsByName(hash) 
        //Find the where you want to scroll
        const position = link[0].getBoundingClientRect().y 
        let top = 0

        let smooth = setInterval(() => {
            let leftover = position - top
            if (top === position) {
                clearInterval(smooth)
            }

            else if(position > top && leftover < 10) {
                top += leftover
                window.scrollTo(0, top)
            }

            else if(position > (top - 10)) {
                top += 10
                window.scrollTo(0, top)
            }

        }, 6)//6 milliseconds is the faster chrome runs setInterval
    }
}

respondido 04 nov., 17:18

Añadiendo esto:

function () {
    window.location.hash = href;
}

está anulando de alguna manera el desplazamiento vertical

top - 72

en Firefox e IE, pero no en Chrome. Básicamente, la página se desplaza suavemente hasta el punto en el que debería detenerse en función del desplazamiento, pero luego salta hasta donde iría la página sin el desplazamiento.

Agrega el hash al final de la URL, pero presionar hacia atrás no lo lleva de regreso a la parte superior, simplemente elimina el hash de la URL y deja la ventana de visualización donde se encuentra.

Aquí está el js completo que estoy usando:

var $root = $('html, body');
$('a').click(function() {
    var href = $.attr(this, 'href');
    $root.animate({
        scrollTop: $(href).offset().top - 120
    }, 500, function () {
        window.location.hash = href;
    });
    return false;
});

respondido 01 nov., 13:18

Esta solución también funcionará para las siguientes URL, sin romper los enlaces de anclaje a diferentes páginas.

http://www.example.com/dir/index.html
http://www.example.com/dir/index.html#anchor

./index.html
./index.html#anchor

etc.

var $root = $('html, body');
$('a').on('click', function(event){
    var hash = this.hash;
    // Is the anchor on the same page?
    if (hash && this.href.slice(0, -hash.length-1) == location.href.slice(0, -location.hash.length-1)) {
        $root.animate({
            scrollTop: $(hash).offset().top
        }, 'normal', function() {
            location.hash = hash;
        });
        return false;
    }
});

Aún no lo he probado en todos los navegadores.

Respondido 11 Feb 16, 23:02

Esto facilitará que jQuery pueda discernir su hash objetivo y saber cuándo y dónde detenerse.

$('a[href*="#"]').click(function(e) {
    e.preventDefault();
    var target = this.hash;
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});

Respondido 25 Feb 16, 18:02

$("a").on("click", function(event){
    //check the value of this.hash
    if(this.hash !== ""){
        event.preventDefault();

        $("html, body").animate({scrollTop:$(this.hash).offset().top}, 500);

        //add hash to the current scroll position
        window.location.hash = this.hash;

    }



});

Respondido el 24 de Septiembre de 16 a las 11:09

Código probado y verificado

<script>
jQuery(document).ready(function(){
// Add smooth scrolling to all links
jQuery("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
  jQuery('html, body').animate({
    scrollTop: jQuery(hash).offset().top
  }, 800, function(){

    // Add hash (#) to URL when done scrolling (default click behavior)
    window.location.hash = hash;
  });
} // End if
});
});
</script>

Respondido el 22 de diciembre de 16 a las 08:12

Para obtener una lista más completa de métodos para un desplazamiento suave, consulte mi respuesta aquí.


Puedes usar window.scroll() a behavior: smooth y top establecido en la parte superior de desplazamiento de la etiqueta de anclaje, lo que garantiza que la etiqueta de anclaje esté en la parte superior de la ventana gráfica.

document.querySelectorAll('a[href^="#"]').forEach(a => {
    a.addEventListener('click', function (e) {
        e.preventDefault();
        var href = this.getAttribute("href");
        var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]");
        //gets Element with an id of the link's href 
        //or an anchor tag with a name attribute of the href of the link without the #
        window.scroll({
            top: elem.offsetTop, 
            left: 0, 
            behavior: 'smooth' 
        });
        //if you want to add the hash to window.location.hash
        //you will need to use setTimeout to prevent losing the smooth scrolling behavior
       //the following code will work for that purpose
       /*setTimeout(function(){
            window.location.hash = this.hash;
        }, 2000); */
    });
});

Demostración:

a, a:visited{
  color: blue;
}

section{
  margin: 500px 0px; 
  text-align: center;
}
<a href="#section1">Section 1</a>
<br/>
<a href="#section2">Section 2</a>
<br/>
<a href="#section3">Section 3</a>
<br/>
<a href="#section4">Section 4</a>
<section id="section1">
<b style="font-size: 2em;">Section 1</b>
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.

Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.

Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.

Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.

Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/>
<section>
<section id="section2">
<b style="font-size: 2em;">Section 2</b>
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.

Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.

Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.

Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.

Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<section>
<section id="section3">
<b style="font-size: 2em;">Section 3</b>
<p>
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.

Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.

Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.

Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.

Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<section>
<a style="margin: 500px 0px; color: initial;" name="section4">
<b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b>
</a>
<p>
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.

Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.

Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.

Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.

Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<script>
document.querySelectorAll('a[href^="#"]').forEach(a => {
        a.addEventListener('click', function (e) {
            e.preventDefault();
            var href = this.getAttribute("href");
            var elem = document.querySelector(href)||document.querySelector("a[name="+href.substring(1, href.length)+"]");
            window.scroll({
                top: elem.offsetTop, 
                left: 0, 
                behavior: 'smooth' 
            });
        });
    });
</script>

Puede simplemente establecer la propiedad CSS scroll-behavior a smooth (que admite la mayoría de los navegadores modernos) lo que evita la necesidad de Javascript.

html, body{
  scroll-behavior: smooth;
}
a, a:visited{
  color: blue;
}

section{
  margin: 500px 0px; 
  text-align: center;
}
<a href="#section1">Section 1</a>
<br/>
<a href="#section2">Section 2</a>
<br/>
<a href="#section3">Section 3</a>
<br/>
<a href="#section4">Section 4</a>
<section id="section1">
<b style="font-size: 2em;">Section 1</b>
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.

Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.

Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.

Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.

Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.<p/>
<section>
<section id="section2">
<b style="font-size: 2em;">Section 2</b>
<p>Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.

Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.

Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.

Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.

Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<section>
<section id="section3">
<b style="font-size: 2em;">Section 3</b>
<p>
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.

Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.

Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.

Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.

Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>
<section>
<a style="margin: 500px 0px; color: initial;" name="section4">
<b style="font-size: 2em;">Section 4 <i>(this is an anchor tag, not a section)</i></b>
</a>
<p>
Lorem ipsum dolor sit amet, et vis laudem utroque, iusto forensibus neglegentur eu duo. Eu pro fuisset salutandi philosophia, discere persecuti qui te. Eos ad quodsi dissentias, ei odio viris signiferumque mei. Putent iuvaret perpetua nec eu. Has no ornatus vivendum. Adhuc nonumes ex vim, in suas rebum graecis mei, usu ad causae recusabo. Idque vituperata vel ea.

Veri verterem pro ex. Ad error omnes est, id sit lorem legendos. Eos vidit ullum ne, tale tantas omittam est ut. Nobis maiorum efficiendi eu mei. Eos et debet placerat signiferumque. Per eu propriae electram.

Impetus percipit menandri te ius, mea ne stet posse fabellas. Aliquid corrumpit vel no, mei in diam praesent contentiones. Qui veniam suscipit probatus ex. No autem homero perfecto quo, eos choro facilis ut. Te quo cibo interesset. Vel verear praesent in, menandri deserunt ad his.

Labore admodum consetetur has et. Possit facilisi eu sed, lorem iriure eum id, pri ei consul necessitatibus. Est te iusto epicuri. Vis no graece putent mentitum, rebum facete offendit nec in. In duis vivendo sed, vel id enim voluptatibus. Velit sanctus ne mel, quem sumo suavitate mel cu, mea ea nullam feugiat.

Tincidunt suscipiantur no pro. Vel ut novum mucius molestie, ut tale ipsum intellegebat mei, mazim accumsan voluptaria ea nam. Posidonium theophrastus ut sea, stet viris hendrerit pro ex, sonet mentitum ne quo. Vim duis feugiat ex, nec eu probo doming persecuti. Velit zril nam in, est commodo splendide id. Et aperiri fuisset iracundia usu. Eu nec iusto audire repudiare.</p>

Respondido 03 ago 21, 16:08

Hice esto para los anclajes href "/ xxxxx # asdf" y "#asdf"

$("a[href*=#]").on('click', function(event){
    var href = $(this).attr("href");
    if ( /(#.*)/.test(href) ){
      var hash = href.match(/(#.*)/)[0];
      var path = href.match(/([^#]*)/)[0];

      if (window.location.pathname == path || path.length == 0){
        event.preventDefault();
        $('html,body').animate({scrollTop:$(this.hash).offset().top}, 1000);
        window.location.hash = hash;
      }
    }
});

Respondido 24 Abr '14, 19:04

Aquí está la solución que implementé para múltiples enlaces y anclajes, para un desplazamiento suave:

http://www.adriantomic.se/development/jquery-localscroll-tutorial/ si tiene sus enlaces de navegación configurados en un div de navegación y declarados con esta estructura:

<a href = "#destinationA">

y sus destinos de etiqueta de ancla correspondientes como tal:

<a id = "destinationA">

Luego simplemente cargue esto en el encabezado del documento:

    <!-- Load jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

<!-- Load ScrollTo -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>

<!-- Load LocalScroll -->
<script src="http://flesler-plugins.googlecode.com/files/jquery.localscroll-1.2.7-min.js"></script>

<script type = "text/javascript">
 $(document).ready(function()
    {
        // Scroll the whole document
        $('#menuBox').localScroll({
           target:'#content'
        });
    });
</script>

Gracias a @Adriantomic

Respondido el 02 de diciembre de 14 a las 18:12

Si tiene un botón simple en la página para desplazarse hacia abajo a un div y desea el botón de retroceso para trabajar saltando a la parte superior, solo agregue este código:

$(window).on('hashchange', function(event) {
    if (event.target.location.hash=="") {
        window.scrollTo(0,0);
    }
});

Esto podría extenderse para saltar a diferentes divs también, leyendo el valor hash y desplazándose como la respuesta de Joseph Silbers.

respondido 10 mar '15, 18:03

Nunca olvide que la función offset () le da la posición de su elemento para documentar. Entonces, cuando necesite desplazar su elemento en relación con su padre, debe usar esto;

    $('.a-parent-div').find('a').click(function(event){
        event.preventDefault();
        $('.scroll-div').animate({
     scrollTop: $( $.attr(this, 'href') ).position().top + $('.scroll-div').scrollTop()
     }, 500);       
  });

El punto clave es obtener scrollTop de scroll-div y agregarlo a scrollTop. Si no lo hace, la función position () siempre le da diferentes valores de posición.

Respondido 15 Jul 16, 18:07

gracias por compartir, Joseph Silber. Aquí su solución 2018 como ES6 con un pequeño cambio para mantener el comportamiento estándar (desplácese hacia arriba):

document.querySelectorAll("a[href^=\"#\"]").forEach((anchor) => {
  anchor.addEventListener("click", function (ev) {
    ev.preventDefault();

    const targetElement = document.querySelector(this.getAttribute("href"));
    targetElement.scrollIntoView({
      block: "start",
      alignToTop: true,
      behavior: "smooth"
    });
  });
});

Respondido 18 Jul 18, 09:07

Requiere jquery y anima para anclar la etiqueta con el nombre especificado en lugar de id, mientras agrega el hash a la URL del navegador. También corrige un error en la mayoría de las respuestas con jquery donde el signo # no tiene como prefijo una barra invertida de escape. El botón de retroceso, desafortunadamente, no navega correctamente a los enlaces hash anteriores ...

$('a[href*=\\#]').click(function (event)
{
    let hashValue = $(this).attr('href');
    let name = hashValue.substring(1);
    let target = $('[name="' + name + '"]');
    $('html, body').animate({ scrollTop: target.offset().top }, 500);
    event.preventDefault();
    history.pushState(null, null, hashValue);
});

Respondido el 04 de Septiembre de 19 a las 16:09

Bueno, la solución depende del tipo de problema, yo uso el método animado javascript para hacer clic en el botón. y utilizo códigos de los siguientes enlaces para la barra de navegación

https://css-tricks.com/snippets/jquery/smooth-scrolling/

$(document).ready(function () {
  $(".js--scroll-to-plans").click(function () {
    $("body,html").animate(
      {
        scrollTop: $(".js--section-plans").offset().top,
      },
      1000
    );
    return false;
  });

  $(".js--scroll-to-start").click(function () {
    $("body,html").animate(
      {
        scrollTop: $(".js--section-features").offset().top,
      },
      1000
    );
    return false;
  });

  $('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      && 
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });
});

Respondido el 30 de junio de 20 a las 16:06

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.