Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...