ID が必要ない場合はhref="#some-value
、ページをスクロールせずに、単にウィンドウの位置を変更します。ドキュメント内 (この場合は a タグ上)が必要な場合id
は、場所の変更によってスクロールが発生します。これを回避する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;
}
});