"window.location.hash = location.hash"在Webkit中不起作用(Safari和Chrome)

Bra*_*dev 7 javascript safari webkit google-chrome

我无法window.location.hash = location.hash在Safari中工作.

我正在使用javascript来封装我的页面内容,其中包含一个可滚动的DIV,位于我网页的导航栏下方.由于当javascript运行时滚动条的位置被重置,我丢失了URL设置的原始哈希位置.我需要重新提示哈希位置,而无需使用javascript重新加载页面,所以我正在使用window.location.hash = location.hash.它适用于IE8,Firefox和Opera,但它在Safari中不起作用.(我也会假设Chrome,但我没有检查).有什么建议?

提示:我喜欢jQuery.

Bra*_*dev 11

Webkit有两个奇怪的东西阻止window.location.hash = location.hash正常工作.

  1. Webkit响应window.location.href而不是window.location.hash(像所有其他浏览器一样).奇怪的是,webkit仍然可以hash使用读取URL的标签location.hash
  2. Webkit有一个记录在案的错误,在location浏览器转到新位置之前,必须将href 设置为相同的位置两次.Bug报告在这里.

这段代码解决了我的问题:(使用jQuery).

$(document).ready(function() {
    gotoHASH()
};

function gotoHASH() {
    if (location.hash) {
        if ( $.browser.webkit == false ) {
            window.location.hash = location.hash;
        } else {
            window.location.href = location.hash;
        }
    }
};
Run Code Online (Sandbox Code Playgroud)


Mic*_*dry 7

我结束了

window.location.hash = "";
window.location.hash = "myanchor";
Run Code Online (Sandbox Code Playgroud)

这在我测试过的所有桌面浏览器以及iOS和Android chrome上运行良好.