Javascript
[Jquery] 메뉴 버튼 클릭 시 특정 위치로 스크롤 이동
- 2022.07.01 15:01:21
[!]HTML[/!]
<ul id="gnb">
<li class="first"><a href="#">main</a></li> <li><a href="#">menu1</a></li> <li><a href="#">menu2</a></li> </ul> </ul> <div id="landing"> <article class="section visual"> <div class="mtit"> <h3>visual</h3> </div> </article> <article class="section menu1"> <div class="mtit"> <h3>‘menu1</h3> </div> </article> <article class="menu2"> <div class="mtit"> <h3>menu2</h3> </div> </article> </div> [!]CSS[/!] #landing .section {min-height: 100vh;display: flex;justify-content: center;align-items: center;}
#landing .section:nth-child(even) {background: #333;} #landing .section:nth-child(even) .mtit > h3 {color: #fff;} .mtit {display: flex;justify-content: center;align-items: center;flex-direction: column;} .mtit > * {display: block;text-align: center;} .mtit > h3 {font-size: 32px;line-height: 42px;color: #333;font-weight: 700;} [!]Jquery[/!] //section target
section_target = { 'init' : function(){ this.action(); }, 'action' : function(){ //aside Active 처리 var $ele = { 'win' : $(window), 'sec' : $('#landing .section'), 'btnWrap' : $('#gnb'), 'btnOn' : $('#gnb > li'), 'btn' : '#gnb > li > a', } var wh = []; var secNum = 0; $ele.sec.each(function(i){ wh[i] = $ele.sec.eq(i).offset().top; }); $(document).on('click', $ele.btn, function(e){ var i = $(this).parent('li').index(); var pos = $('.section').eq(i).offset().top; e.preventDefault(); $('html,body').animate({ 'scrollTop' : pos },600,'easeInOutQuart'); return false; }); function acc(){ $ele.btnOn.eq(secNum).addClass('active').siblings().removeClass('active'); if(secNum==0){ $ele.btnWrap.addClass('home-on'); }else{ $ele.btnWrap.removeClass('home-on'); } } acc(); $ele.win.on({ 'load scroll resize' : function(){ var sh = parseInt($(this).scrollTop()); for (i=0; i < $ele.sec.length; i++){ if(sh >= parseInt(wh[i]) - ($ele.win.height()/2)){ secNum = i; acc(); } } } }); } } $(function(){ $(window).on({ 'load' : function(){ if($('#landing .section').length>0){ section_target.init(); } } }); }) 참고 사이트 : 노랑강정 |