开发者

window.location.hash = " "; prevent scrolling to the top?

开发者 https://www.devze.com 2023-02-04 22:20 出处:网络
in my website i set the url adress using window.location.hash = \'project_name\'; but if i want to clean the adress url from any hashes (when i close a project) and i set

in my website i set the url adress using

window.location.hash = 'project_name';

but if i want to clean the adress url from any hashes (when i close a project) and i set

window.location.hash = '';

it happens the page scrolls up to the top page

there is开发者_开发问答 any way to clean up the url without any side effect?

thanks


There's the onhashchange event, but it cannot be cancelled reliably across browsers to prevent scrolling. The best solution is to record the scroll position before changing the hash location and reset it afterwards. For example, the following code will catch a click on any link ― that doesn't stop propagation ― with a href value of # and prevent the page from scrolling vertically:

document.onclick = function (evt) {
    var tgt = (evt && evt.target) || event.srcElement,
        scr = document.body.scrollTop;

    if (tgt.tagName == "A" && tgt.href.slice(-1) == "#") {
        window.location.href = "#";
        document.body.scrollTop = scr;           
        return false;
    }
}

If you're changing the hash through script, you can use the following code:

var scr = document.body.scrollTop;
window.location.href = '#';
document.body.scrollTop = scr;

Either of those methods can be adjusted to avoid scrolling individual elements or scrolling the page horizontally. Note that you can remove the entire hash (including the #) without causing navigation or scrolling in modern browsers by calling the pushState or replaceState functions.


I was having the same problem and came here for an answer. Just found out there is a very easy way:

window.location.hash = ' ';

Basically you are setting it to '# ', since the space doesn't exist, it doesn't move. When you revisit the page, it also doesn't treat it any differently than just #


First off, thanks for your solutions - @Andy-E and @JustMaier.

However, I had a problem getting it to work based on Andy E's second code block in Firefox and JustMaier's code in chrome.

So I did a mash up of those two code blocks and it works just as intended on both browsers

var scr = document.body.scrollTop;

window.location.hash = ' ';

document.body.scrollTop = scr;


My two cents, taking nothing away from the real JS ninjas, mentioned above. : )


document.body.scrollTop is deprecated, also latest Chrome versions seem to be unstable here. The following should work:

  var topPos = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
  window.location.href = '#';
  document.documentElement.scrollTop = topPos;
0

精彩评论

暂无评论...
验证码 换一张
取 消