페이지 이동후 원하는 곳까지 부드럽게 스크롤되게 하기
- 퍼블리셔/jQuery
- 2019. 6. 5. 11:21
문서를 만들다보면 해당페이지로 이동후 원하는 위치까지 스크롤이 되는 경우를 원할때가 있습니다.
이때 문서가 html 이든 jsp(do), asp 든 상관없이 원하는 액션이 되길 원합니다.
이런 액션이 종종 있어서 아예 만들어봤습니다.
필요한 부분
- index.html: 이동하기전 보여져야할 페이지(링크가 있는 페이지)
- target.html: 최종 이동할 페이지(스크롤할 영역이 있는 페이지)
- main.js: 해당영역까지 부드럽게 스크롤이 될 스크립트
아래 페이지의 내용은 이렇습니다.
링크를 보시면 'target.html#section1' 형식입니다. '해당페이지#해당영역아이디'
index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>index</title>
</head>
<body>
<a class="section3" href="target.html#section1">
<div>
<p>Go to section scroll-section1</p>
</div>
</a>
<a class="section3" href="target.html#section2">
<div>
<p>Go to section scroll-section2</p>
</div>
</a>
<a class="section3" href="target.html#section3">
<div>
<p>Go to section scroll-section3</p>
</div>
</a>
<a class="section3" href="target.html#section4">
<div>
<p>Go to section scroll-section4</p>
</div>
</a>
</body>
</html>
id 영역을 잡고 보기편하게 높이값을 1000px 를 지정하고 배경색을 지정했습니다.
target.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>scroll</title>
<style>
* { margin: 0; padding: 0; }
section { color: #fff; height: 1000px; text-align: center; line-height: 1000px; font-size: 5em;}
.bg1 { background-color: #f30; }
.bg2 { background-color: #630; }
.bg3 { background-color: #a06; }
.bg4 { background-color: #660; }
</style>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<section class="bg1" id="scroll-section1">
<p>section 1</p>
</section>
<section class="bg2" id="scroll-section2">
<p>section 2</p>
</section>
<section class="bg3" id="scroll-section3">
<p>section 3</p>
</section>
<section class="bg4" id="scroll-section4">
<p>section 4</p>
</section>
</body>
</html>
주소값 page_url 을 가지고와서 substring으로 문자열을 추출하는데 lastIndexOf로 마지막문자열을 검색하여 page_id 변수에 담습니다.
'#scroll-' + page_id 영역까지 스크롤합니다.
main.js
$(document).ready(function () {
var page_url = window.location.href;
var page_id = page_url.substring(page_url.lastIndexOf("#") + 1);
// alert(page_id);
if (page_id == 'section1') {
$('html, body').animate({
scrollTop: $('#scroll-' + page_id).offset().top
}, 500);
} else if (page_id == 'section2') {
$('html, body').animate({
scrollTop: $('#scroll-' + page_id).offset().top
}, 500);
} else if (page_id == 'section3') {
$('html, body').animate({
scrollTop: $('#scroll-' + page_id).offset().top
}, 500);
} else if (page_id == 'section4') {
$('html, body').animate({
scrollTop: $('#scroll-' + page_id).offset().top
}, 500);
}
});
파일을 다운로드해서 사용해보세요.