阻止设置location.hash时的默认行为

4

当我这样做时,

location.hash = "test"

URL已更新,页面将聚焦于具有该ID的元素。

有没有办法阻止页面聚焦到该元素?


2
location.hash与jQuery无关,它是JavaScript的一部分。jQuery是JavaScript框架。 - Tadeck
@Tadeck 我正在使用那个框架。只要解决方案能够正常工作,它是纯JS还是jQuery对我来说并不重要。 - developarvin
@Zirak 它用于选项卡历史记录。它运行良好。我只是出于美观原因不想聚焦于该元素。 - developarvin
请查看历史记录API - Zirak
@arvinsim:看看我的“绕过”答案,虽然我不建议你使用它(最好重新考虑代码,如果你不想移动到页面的目标部分,则不要更改location.hash)。此外,关于jQuery与JavaScript语句:当转向更高级的项目时,即使基于jQuery,您也需要详细了解JavaScript-您需要知道它在后台如何工作以及如何使用其概念,更多信息请参见:http://programmers.stackexchange.com/questions/40845/how-necessary-is-it-to-learn-javascript-before-jquery - Tadeck
显示剩余4条评论
2个回答

3

解决方案

你无法阻止此行为,但是你可以通过临时隐藏目标来愚弄它,例如像这样(与jQuery无关):

// obtain "target" DOM (not jQuery) element and do this:
var original_id = target.id; // save original ID
target.id = null; // set target's ID
location.hash = 'test'; // issue location.hash change
target.id = original_id; // set ID to original value

通用解决方案

或者更一般的例子:

// make target_hash set to a hash you want to not lead you to page section and:
var element = document.getElementById(target_hash); // find element by ID
var original_id = element.id; // save original ID
location.hash = target_hash; // previously defined by you (eg. 'test')
element.id = original_id; // reset ID

演示/证明

以下是一个实时例子,在通过jQuery附加的事件处理程序中,可以如下操作(演示在此处:http://jsfiddle.net/DaZfH/):

some_link.on('click', function(event){
    event.preventDefault();
    var target = document.getElementById('target');
    var original_id = target.id;
    target.id = null; // unset ID
    location.hash = 'target';
    target.id = original_id;
});

免责声明

但的确,其他人是正确的:将您移至文档中的正确位置是正确的行为。如果您正在执行我提到的操作,那么您的解决方案相当粗糙,并且肯定有更好的方法来解决这个问题。


1
有没有办法阻止页面定位到该元素?
有的。虽然hashchange事件无法取消,但您可以通过以下方法重置其不需要的行为。

var popY,
    popX;

//When location.hash is changed, popstate is the first event to fire 
//Use this event to record current state

window.addEventListener('popstate', popstateHandler);
function popstateHandler() {
  popY = window.scrollY;
  popX = window.scrollX;
}

//Reset scroll position with recorded values when hashchange fires (after page is scrolled)

window.addEventListener('hashchange', hashchangeHandler);
function hashchangeHandler() {
  window.scrollTo(popX, popY);
}

这就是它的基础。你可能想要为IE进行一些校对,并实现你做这个的原因:滚动动画,激活某些内容等。

scrollY、scrollX的Polyfill:

if(!('scrollY' in window)) {
    Object.defineProperty(window, 'scrollY', {
        get: function () {
            return window.pageYOffset
        }
    });
    Object.defineProperty(window, 'scrollX', {
        get: function () {
            return window.pageXOffset
        }
    })
}


使用这种方法在技术上是可行的,但有时我会看到由于来回跳跃而引起的闪烁(浏览器:Chromium)。 - jneuendorf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接