当我这样做时,
location.hash = "test"
url 会更新,页面会定位到具有该 id 的元素。
有没有办法阻止页面定位到该元素?
Solution
您无法阻止这种行为,但您可以通过暂时隐藏目标来愚弄它,例如。像这样(与 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/ 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;
});
免责声明
但其他人确实是对的:将您移动到文档中的正确位置是正确的行为。如果你正在做像我提到的那样的事情,那么你的解决方案就相当哈克了,而且肯定有更好的方法来做到这一点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)