jquery - 버튼 클릭시 원하는 곳으로 부드럽게 이동하기 페이지 새로고침
버튼을 클릭하면 원하는 곳으로 부드럽게 이동 합니다. '버튼1'과 '버튼2'를 클릭하면서 어디로 이동하는지 스크롤에 위치를 확인하세요.
html
<ul class="anchor_tab">
<li><a href="#" data-anchor="anchor_div1">버튼1</a></li>
<li><a href="#" data-anchor="anchor_div2">버튼2</a></li>
</ul>
<div id="anchor_div1">
버튼1을 클릭했을때 이동했을때 내용
</div>
<div id="anchor_div2">
버튼2을 클릭했을때 이동했을때 내용
</div>
버튼 anchor_div1 이름은 원하는 이름으로 하되, 클릭 했을때 이동되는 id하고 이름이 같아야합니다. ex) <div id="anchor_div1">이동했을때 내용</div>
css
.anchor_tab{margin:0;padding:0;overflow:hidden}
.anchor_tab li{float:left;margin:0 5px}
.anchor_tab li a{display:inline-block;height:30px;padding:0 15px;border:1px solid #ccc;border-radius:5px;background:#f4f4f4;box-shadow:0 0 5px #eee;color:#333;text-align:center;font-size:14px;line-height:30px}
.anchor_tab li a:hover{border:1px solid #1e7ae2;color:#1e7ae2;text-decoration:none}
#anchor_div1,#anchor_div2{margin-bottom:10px;padding:10px;background:#f4f4f4;border:1px solid #ccc;border-radius:5px}
스타일은 본인에 맞게 꾸며주세요.
script
$(document).ready(function(){
/* 탭 클릭 */
$('.anchor_tab li a').on('click',function(){
var anchorId = $(this).attr('data-anchor');
// 스크롤 이동
scroll_to_anchor_tab(anchorId);
});
});
// 탭 이동 - 부드러운 스크롤
function scroll_to_anchor_tab(anchor_id,speed) {
if( !speed ) var speed = 'slow';
var a_tag = $("#"+anchor_id);
if(a_tag.length > 0){
$('html, body').animate({
scrollTop: a_tag.offset().top - $('').height() - $('').height() // 상단에 특정 위치를 제외하고 스크롤할때 해당 이름 작성
}, speed);
}
}
버튼1을 클릭했을때 이동했을때 내용
버튼2을 클릭했을때 이동했을때 내용
* 참고로 스크롤 될만큼의 내용이 페이지에 있어야 효과가 더 잘 나타납니다.
해당 팁이 유용했다면, 눌러주세요.