JS에서 URL 앵커 변경 이벤트 처리
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, Opera 10.60 , Firefox 3.6 및 Internet Explorer 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에는 해시 변경 이벤트를 확인하고 필요한 경우 자체 제공하는 플러그인도 있습니다 ( http://benalman.com/projects/jquery-hashchange-plugin/) .
편집 : 업데이트 된 브라우저 지원 (다시).
setInterval()
현재로서는 유일한 범용 솔루션입니다. 하지만 미래에는 해시 체인지 이벤트의 형태로 약간의 빛이 있습니다.
다른 SO 질문에서 볼 수 있듯이 유일한 브라우저 간 솔루션은 타이머입니다. 예를 들어이 질문 을 확인하십시오 .
(기록을 위해.) YUI3 "hashchange"합성 이벤트는 허용 된 답변과 거의 동일한 작업을 수행합니다.
YUI().use('history-hash', function (Y) {
Y.on('hashchange', function (e) {
// Handle hashchange events on the current window.
}, Y.config.win);
});
addEventListener
덮어 쓰기 대신 사용 하는 것이 좋습니다 window.onhashchange
. 그렇지 않으면 다른 플러그인에 대한 이벤트를 차단합니다.
window.addEventListener('hashchange', function() {
...
})
Looking at the global browser usage today, a fallback is not needed anymore.
You can get more info from this
The mutation event module is designed to allow notification of any changes to the structure of a document, including attr and text modifications.
참고URL : https://stackoverflow.com/questions/2161906/handle-url-anchor-change-event-in-js
'development' 카테고리의 다른 글
경고 : MyProject.csproj를 참조하는 모든 프로젝트는 Microsoft.Bcl.Build 너겟 패키지를 설치해야합니다. (0) | 2020.09.14 |
---|---|
## 전 처리기 연산자의 응용 프로그램과 고려해야 할 사항은 무엇입니까? (0) | 2020.09.14 |
jQuery, 체크 박스 및 .is (“: checked”) (0) | 2020.09.14 |
배치 파일의 at 기호 (@)는 무엇이며 어떤 역할을합니까? (0) | 2020.09.14 |
Lisp 개발에 Vim 사용 (0) | 2020.09.14 |