반응형
반응형
a 태그를 이용해 다른 페이지 특정 지점으로 이동할 때, href에 id 값을 넣으면 이동 가능하다.
하지만 header가 보통 absolute로 띄어져있어서 header에 가려지는 문제가 발생해서 이를 해결하기 위한 코드이다.
다른 페이지로 이동하고 페이지 리로르 될 때 url의 #값을 확인해 #값이 있다면 해당 지점으로 이동하게 코딩했다.
<a href="/link#id"></a>
자바스크립트 내용
// 1. 페이지 이동시(페이지 새로 리로드 될때만)
var top_space = 0;
if ($('#header').length) {
top_space = $('#header').outerHeight();
} // 해더영역(빼야할 공간)
var hash = window.location.hash;
if (hash && document.getElementById(hash.slice(1))) { // #값이 있을때만 실행
var $this = $(hash);
$('html, body').animate({
scrollTop: $this.offset().top - top_space
}, 500, function () {
window.history.pushState ? window.history.pushState(null, null, hash) : window.location.hash = hash;
});
}
// 2. 페이지 내에서 스크롤 실행시
$('.nav').on('click', function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top - top_space
}, 500);
return false;
}
}
});
반응형
'JQUERY' 카테고리의 다른 글
[jQuery] html scroll시 특정높이에서 header 변경 (0) | 2022.05.25 |
---|---|
[jQuery] input file 파일명 추출, 추출한 파일명 삽입 (0) | 2022.05.25 |
[jQuery] 특정 영역 밖 영역 클릭 이벤트 - on('click') (0) | 2022.05.25 |
[jQuery] accordian menu - 아코디언 메뉴 만들기 (0) | 2022.05.25 |