Can I update [removed].hash without having the web

2019-03-17 08:06发布

Using JavaScript, is there a way to update window.location.hash without scrolling the web page?

I have clickable title elements that toggle the visibility of a div directly beneath them. I want the /foo#bar in the history when clicking titles but don't want the page scrolling about. So when navigating away from /foo#bar I'll be able to use the back button and have the div whose ID is in window.location.hash be visible upon return.

Is this behavior possible?

6条回答
姐就是有狂的资本
2楼-- · 2019-03-17 08:20

Another thing you could try is changing the id of the element the hash points to temporarily. Worked for me!

function changeHashWithoutScrolling(hash) {
  var id = hash.replace(/^.*#/, ''),
      elem = document.getElementById(id)
  elem.id = id+'-tmp'
  window.location.hash = hash
  elem.id = id
}
查看更多
Fickle 薄情
3楼-- · 2019-03-17 08:24

Wanted to add a comment to Catherines answer but I don't have the rep yet -

Great solution however it wasn't working for me in Chrome as $('html').scrollTop() always returns 0 - a minor edit resolves the issue:

scrollmem = $('html').scrollTop() || $('body').scrollTop();
window.location.hash = hash;
$('html,body').scrollTop(scrollmem);
查看更多
孤傲高冷的网名
4楼-- · 2019-03-17 08:35

This behavior is very much possible. You should look into some of the libraries that have been developed to give you this functionality.

Really Simple History: http://code.google.com/p/reallysimplehistory/ SWFAddress: http://www.asual.com/swfaddress/

查看更多
Summer. ? 凉城
5楼-- · 2019-03-17 08:35

To change the hash without having the page reload/scroll, you can now simply use html5 history.pushState.

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

It's supported by all the major browsers:

http://caniuse.com/history

MDN:

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

Also note that the last url parameter we're using here, it can be any url, so it's not limited to hashes.

查看更多
何必那么认真
6楼-- · 2019-03-17 08:35

As easy as it get

var scrollmem = $('html,body').scrollTop();
window.location.hash = hash;
$('html,body').scrollTop(scrollmem);
查看更多
女痞
7楼-- · 2019-03-17 08:40

Bas on the answer from Sunny I made this function that also avoids undefined and nulls:

    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;
            }
        }
    }
查看更多
登录 后发表回答