如果 id 不是必需的,则只需href="#some-value
更改窗口位置而不滚动页面。如果您确实需要id
在文档中(在这种情况下是在 a 标签上),那么位置更改将导致滚动。您可以通过在现代浏览器中使用该history
对象或将滚动位置存储在链接单击上,然后使用hashchange
事件重置它来解决此问题。
我将在这两种解决方案中使用这个标记:
示例标记:
<div class="filler"></div>
<a id="abc1" href="#abc1" class="my-class">this is an anchor btn</a>
<div class="filler"></div>
<a id="abc2" href="#abc2" class="my-class">this is an anchor btn</a>
<div class="filler"></div>
<a id="abc3" href="#abc3" class="my-class">this is an anchor btn</a>
<div class="filler"></div>
history.replaceState 或 history.pushState
现场演示(点击)。
//get element referneces
var elems = document.getElementsByClassName('my-class');
//iterate over the references
for (var i=0; i<elems.length; ++i) {
//add click function to each element
elems[i].addEventListener('click', clickFunc);
}
//this will store the scroll position
var keepScroll = false;
//fires when a ".my-class" link is clicked
function clickFunc(e) {
//prevent default behavior of the link
e.preventDefault();
//add hash
history.replaceState({}, '', e.target.href);
}
scrollTop 和 hashchange 事件
现场演示(点击)。
JavaScript:
//get element referneces
var elems = document.getElementsByClassName('my-class');
//iterate over the references
for (var i=0; i<elems.length; ++i) {
//add click function to each element
elems[i].addEventListener('click', clickFunc);
}
//this will store the scroll position
var keepScroll = false;
//fires when a ".my-class" link is clicked
function clickFunc(e) {
//if the location hash is already set to this link
if (window.location.hash === '#'+e.target.id) {
//do nothing
e.preventDefault();
}
else {
//the location will change - so store the scroll position
keepScroll = document.body.scrollTop;
}
}
window.addEventListener('hashchange', function(e) {
//the location has has changed
//if "keepScroll has been set
if (keepScroll !== false) {
//move scroll position to stored position
document.body.scrollTop = keepScroll;
//set "keepScroll" to false so that this behavior won't affect irrelevant links
keepScroll = false;
}
});