Puedo actualizar la ventana.ubicación.hash sin tener el desplazamiento de la página web?


Usando JavaScript, hay una manera de actualizar la ventana.ubicación.¿hash sin desplazarte por la página web?

Tengo elementos de título en los que se puede hacer clic que alternan la visibilidad de un div directamente debajo de ellos. Quiero la barra / foo#en el historial al hacer clic en títulos, pero no quiero que la página se desplace. Así que al navegar fuera de / foo#bar voy a ser capaz de utilizar el botón atrás y tener el div cuyo ID está en la ventana.ubicación.hash ser visible al regreso.

¿Es posible este comportamiento?

Author: D_N, 2009-03-14

6 answers

Este comportamiento es muy posible. Usted debe buscar en algunas de las bibliotecas que se han desarrollado para darle esta funcionalidad.

Historia realmente simple: http://code.google.com/p/reallysimplehistory / SWFAddress: http://www.asual.com/swfaddress /

 1
Author: Willem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-14 02:33:26

Tan fácil como se pone

var scrollmem = $('html,body').scrollTop();
window.location.hash = hash;
$('html,body').scrollTop(scrollmem);
 30
Author: Catherine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-19 23:08:00

Para cambiar el hash sin tener que recargar/desplazar la página, ahora puede simplemente usar html5 history.pushState.

history.pushState(null,null,'#hashexample');

Es compatible con todos los principales navegadores:

Http://caniuse.com/history

MDN:

Https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState().C2.A0method

También tenga en cuenta que el último parámetro de url que estamos utilizando aquí, puede ser cualquier url, por lo que no está limitado a hashes.

 29
Author: Stratboy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-15 13:32:25

Otra cosa que podría intentar es cambiar el id del elemento al que apunta el hash temporalmente. ¡Funcionó para mí!

function changeHashWithoutScrolling(hash) {
  var id = hash.replace(/^.*#/, ''),
      elem = document.getElementById(id)
  elem.id = id+'-tmp'
  window.location.hash = hash
  elem.id = id
}
 22
Author: Sunny,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-22 12:08:22

Quería agregar un comentario a la respuesta de Catherines, pero aún no tengo el representante -

Gran solución sin embargo, no estaba funcionando para mí en Chrome como html('html').scrollTop () siempre devuelve 0-una edición menor resuelve el problema:

scrollmem = $('html').scrollTop() || $('body').scrollTop();
window.location.hash = hash;
$('html,body').scrollTop(scrollmem);
 2
Author: Brian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-05 23:29:05

Bajo la respuesta de Sunny hice esta función que también evita indefinidos y nulos:

    function changeHashWithoutScrolling(hash) {
        var id;
        var elem;

        id = hash.replace(/^.*#/, '');

        if (id) {
            elem = document.getElementById(id);

            if (elem) {
                elem.id = id + '-tmp';
                window.location.hash = hash;
                elem.id = id;
            }
        }
    }
 2
Author: tobias47n9e,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-03 11:27:40