简体   繁体   中英

how can I make my navbar scroll smoothly to the top on page click

I am trying to create a site based on this horizontal scrolling method Responsive horizontal page sliding

I want the navbar to be vertically central on the first page, but move to the top on the other pages.

Example: http://jsfiddle.net/wtvaJ/26/

I have this working, but I want the navbar to animate and scroll smoothly to the top when another page is clicked. I have tried doing this

  $('.navbar').animate({scrollTop:50},500); 

but nothing changes. I know its not bad code as it isn't breaking my jquery function but I also know its not correct, as its not working.

Has anybody got any idea on how to make this happen?

All input greatly appreciated

heres the code to match the jsfiddle

HTML

<div class="wrapper">
 <div class="nav">
     <a href="#page-1" class="scrollitem selected">page 1</a>
     <a href="#page-2" class="scrollitem">page 2</a>
     <a href="#page-3" class="scrollitem">page 3</a>
 </div>
 <div id="page-1" class="page"> 
     <h3>page 1</h3>
    <div class="simulate">Simulated content heigher than 100%</div>
 </div>
 <div id="page-2" class="page">  
     <h3>page 2</h3>
    <div class="simulate">Simulated content heigher than 100%</div>
 </div>
 <div id="page-3" class="page"> 
    <h3>page 3</h3>
    <div class="simulate">Simulated content heigher than 100%</div>
 </div>
</div>

JS

$(document).ready(function () {
 var sildeNum = $('.page').length,
    wrapperWidth = 100 * sildeNum,
    slideWidth = 100/sildeNum;
 $('.wrapper').width(wrapperWidth + '%'); 
 $('.page').width(slideWidth + '%');

 $('a.scrollitem').click(function(){
    $('a.scrollitem').removeClass('selected');
    $(this).addClass('selected');

    var slideNumber = $($(this).attr('href')).index('.page'),
        margin = slideNumber * -100 + '%';

    $('.wrapper').animate({marginLeft: margin},1000);

    if(slideNumber=='0'){
            $('.nav').css('position','absolute');
            $('.nav').css('top','30%');
        }else{
            $('.nav').css('position','absolute');
            $('.nav').css('top','0px');
            $('.nav').animate({scrollTop:50},500);
        }
    return false;
 });
});

CSS

html, body {
height: 100%;
margin: 0;
overflow-x:hidden;
position:relative;
}

.wrapper {
height: 100%;
background: #263729;
}
.page {
float:left;
background: #992213;
min-height: 100%;
padding-top: 30px;
}
.simulate{
 height:2000px;
 }

.nav{
 position:absolute;
 top:30%;
 z-index:999;
 left:0;
 width:100%;
 background-color:#CCCCCC;
 height:85px;
}

Just use animate() instead of css() :

if (slideNumber == '0') {
  $('.nav').animate({
    'top': '30%'
  });
} else {
  $('.nav').animate({
    'top': '0'
  });
}

DemoFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM