1. ホーム
  2. javascript

[解決済み] JavascriptでURLフラグメント識別子(アンカー)の変更イベントを処理する

2023-02-22 15:06:46

質問

URL フラグメント識別子(アンカー)の変更時に実行される Javascript コールバックコードはどのように記述すればよいでしょうか?

例えば http://example.com#a から http://example.com#b

どのように解決するのですか?

Google カスタム検索エンジンは、別のドメインにある子 iframe が iframe ドキュメントの本体のサイズを含むように親の位置ハッシュを更新する間、ハッシュを以前の値と比較するためにタイマーを使用します。 タイマーが変更をキャッチすると、親は iframe のサイズを本体のサイズに合わせて変更し、スクロールバーが表示されないようにすることができます。

次のようなものでも同じことが実現できます。

var storedHash = window.location.hash;
window.setInterval(function () {
    if (window.location.hash != storedHash) {
        storedHash = window.location.hash;
        hashChanged(storedHash);
    }
}, 100); // Google uses 100ms intervals I think, might be lower

Google Chrome 5、Safari 5。 オペラ 10.60 , Firefox 3.6 および インターネット エクスプローラ 8 すべて hashchange イベントをサポートします。

if ("onhashchange" in window) // does the browser support the hashchange event?
    window.onhashchange = function () {
        hashChanged(window.location.hash);
    }

とまとめると

if ("onhashchange" in window) { // event supported?
    window.onhashchange = function () {
        hashChanged(window.location.hash);
    }
}
else { // event not supported:
    var storedHash = window.location.hash;
    window.setInterval(function () {
        if (window.location.hash != storedHash) {
            storedHash = window.location.hash;
            hashChanged(storedHash);
        }
    }, 100);
}

jQuery には、hashchange イベントをチェックし、必要に応じて独自のイベントを提供するプラグインもあります - 。 http://benalman.com/projects/jquery-hashchange-plugin/ .

EDIT : ブラウザサポートを更新しました(再掲)。