0
以下はJSコードです。アンカーリンクをスクロールしたページがあります。セクションの基本的な見出しをカバーすることなく、リンクがクリックされたときにページ上の特定のセクションに移動する必要があります。アンカーリンクのオフセットが最初のクリックでのみ機能しない
これは私が達成できたことです(もちろん、Stackoverlfow sleuthingの助けを借りて)。
// The function actually applying the offset
function offsetAnchor() {
if(location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}
// This will capture hash changes while on the page
window.addEventListener("hashchange", offsetAnchor);
// This is here so that when you enter the page with a hash,
// it can provide the offset in that case too. Having a timeout
// seems necessary to allow the browser to jump to the anchor first.
window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and may not always work right (although it did in my testing).
上記のコードはうまくいくようですが、問題は2回目のアンカーをクリックしたときからのみ問題になります。なぜそれは最初のネクタイ自体に発射されないのですか?私はそれがハッシュチェンジに関連していることを知っているので、ハッシュチェンジがあるので、javascriptは2番目のリンクからピックアップしています。私に解決策を教えてもらえますか?
に役立ちます:) – TheEarlyMan