简体   繁体   中英

CSS Div Scroll Height

I am trying to recreate the effect seen here: http://jsfiddle.net/surendraVsingh/aATHd/2/

But I am trying to animate the height. For some reason, it works fine when I scroll down, but upon scrolling up, the height doesn't change back to normal. Any ideas?

Here is what I have now: http://justinledelson.com/new/

$(window).scroll(function(){
    if ($(this).scrollTop() > 250){
     $('#header').animate({"height":"100px"}, 1500);
  } 
  else{
    $('#header').animate({"height":"470px"}, 1);
  }
});

Thanks!

Although I said that this wasn't a solution for your problem, it seems that it's actually a solution.

Add a class after each action. Something like expanded and collapsed for each situation, and check if that class is present before doing the animation. That way the animations won't trigger until it's necessary.

This avoids triggering the animation multiple times queuing the animation. That's why if you scrolled down a lot of times and scrolled back to top, the "expanding" animation triggered long after you scrolled up (it had to wait that each "collapsing" animation ended)

My test was:

$(window).scroll(function(){ 
    var $header = $('#header');
    if ($(this).scrollTop() > 50){  // x should be from where you want this to happen from top//
     if (!$header.hasClass('collapsed')) {
       $header.animate({"height":"100px"}, 1500, function() {
         $header.toggleClass('expanded collapsed');
       });
     }
    } 
    else{
      if (!$header.hasClass('expanded')) {
        $header.animate({"height":"470px"}, 1, function() {
         $header.toggleClass('expanded collapsed');
       });
      }
    }

});

header should start with expanded class

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