2011-01-11 9 views
5

Duplicar posibles:
Modifying document.location.hash without page scrolling¿Cómo evito que el navegador salte a un ancla cuando se le cambia el identificador de fragmento de la URL?

Me gustaría cancelar el evento, si es posible, pero no veo ningún precedente para esto. Supongamos por el momento que estoy obligado a usar la misma cadena para mi identificador de fragmento y el nombre de mi ancla. Necesito interceptar el evento y cancelarlo de alguna manera.

ACTUALIZACIÓN: Este es un duplicado de Modifying document.location.hash without page scrolling

+0

Cambió cómo? Por el usuario? –

+0

Aquí hay un código que lo hace, lo intentaré y lo encontraré :) – alex

+1

Posible duplicado de: http://stackoverflow.com/questions/1489624/modifying-document-location-hash-without-page-scrolling – scoffey

Respuesta

0

Tal vez?

<h1 id="header">home</h1> 
<ul> 
    <li><a href="#home">Home</a></li> 
    <li><a href="#product">Product</a></li> 
    <li><a href="#about">About</a></li> 
</ul> 
<script type="text/javascript"> 

    window.onload = function(e) { 
    var links = document.getElementsByTagName('a'); 
    for (var i=0; i < links.length; i++) { 
     links[i].addEventListener('click', function(e) { 
      var hash = this.href.split('#')[1]; 
      if(hash.length) { 
       if(hash == 'product') { 
        alert('Sorry, page in development'); 
        e.preventDefault(); 
       }else{ 
        document.getElementById('header').innerHTML = hash; 
       } 
      } 
     }, false); 
    }; 
    }; 
    // OR 
    window.onhashchange = function(e) { 
     var hash = window.location.hash.substr(1); 
     if(hash.length) { 
      if(hash == 'product') { 
       alert('Sorry, page in development'); 
       window.history.back(); 
      }else{ 
       document.getElementById('header').innerHTML = hash; 
      } 
     } 
    }; 

</script> 
Cuestiones relacionadas