window.location.hash ="英寸;防止滚动到顶部? [英] window.location.hash = " "; prevent scrolling to the top?

查看:194
本文介绍了window.location.hash ="英寸;防止滚动到顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网站上我使用

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?

谢谢

推荐答案

onhashchange 事件,但不能在浏览器之间可靠地取消它以防止滚动。最好的解决方案是在更改哈希位置之前记录滚动位置,然后重置它。例如,以下代码将捕获任何链接上的点击 - 不会停止传播 - href值为并阻止页面垂直滚动:

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;

可以调整其中任何一种方法,以避免滚动单个元素或水平滚动页面。请注意,您可以 删除整个哈希值(包括)通过调用 pushState replaceState 函数,不会在现代浏览器中导致导航或滚动。

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.

这篇关于window.location.hash ="英寸;防止滚动到顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆