当我这样做时,
location.hash = "test"
URL已更新,页面将聚焦于具有该ID的元素。
有没有办法阻止页面聚焦到该元素?
当我这样做时,
location.hash = "test"
URL已更新,页面将聚焦于具有该ID的元素。
有没有办法阻止页面聚焦到该元素?
你无法阻止此行为,但是你可以通过临时隐藏目标来愚弄它,例如像这样(与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;
});
但的确,其他人是正确的:将您移至文档中的正确位置是正确的行为。如果您正在执行我提到的操作,那么您的解决方案相当粗糙,并且肯定有更好的方法来解决这个问题。
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
}
})
}
location.hash
与jQuery无关,它是JavaScript的一部分。jQuery是JavaScript框架。 - Tadecklocation.hash
)。此外,关于jQuery与JavaScript语句:当转向更高级的项目时,即使基于jQuery,您也需要详细了解JavaScript-您需要知道它在后台如何工作以及如何使用其概念,更多信息请参见:http://programmers.stackexchange.com/questions/40845/how-necessary-is-it-to-learn-javascript-before-jquery - Tadeck