2010-10-26 14 views
5

Al cargar una página Me gustaría que vaya al #content sin cambiar la URL.Ir al ancla sin cambiar la URL

pensé que iba a ser capaz de utilizar

window.location.hash = "content"; 
window.location.replace("#content", ""); 

pero #content todavía existe en la url.

¿Algún método mejor?


Editar:

también intentó

window.location.hash = "content"; 
window.location.replace(window.location.toString().replace("#content", "")); 

Pero esto envía el navegador en un bucle.

Respuesta

3

Puede encontrar la posición vertical del ancla con esa identificación, y luego desplazarse a esa posición.

+0

tan fácil. ¡Gracias! –

0

Esto lo hará con una bonita animación:

<a href="#link">Click to scroll</a> 

<div id="link" style="margin-top: 1000px; height: 300px; background-color: blue; margin-bottom: 1000px"> 
    Click and scroll to this div without changing url! 
</div> 


<script> 
    $('a').on('click', function(e) { 
     // prevent default anchor click behavior 
     e.preventDefault(); 

     // store hash 
     var hash = this.hash; 

     if ($(hash).length) { 
      $('html, body').animate({ 
       scrollTop: $(hash).offset().top 
      }, 300, function() { 
       // Do something fun if you want! 
      }); 
     } 
    }); 
</script> 

Working JSFiddle

Cuestiones relacionadas