質問

I have a div that is fixed at the top of the page, which holds the navigation to the website. It has a height of 175px. This DIV will remain on show as you scroll down the page.

I would like this div to shrink to a height of 90px when the user has scrolled down the page 175px and remain at 90px as they scroll down the page. When they scroll back up to the top, I'd like the DIV to grow back to its original 175px height.

I'd like this to animate when doing so (preferably slide up and slide down) and would prefer to use CSS3 to do so...

Here is a fiddle of what I have so far but because I'm a query noob, not sure how to go about things… http://jsfiddle.net/bnsUB/

EDIT: I forgot to mention that I also have content within this DIV that will need its paddings etc. adjusted whilst the container slides up/down. So if those padding values could shrink/grow as well then that would be an added bonus

役に立ちましたか?

解決

You need to trigger an action based on the current $.scrollTop() value of the window.

Something like:

$(document).scroll(function(){
    if ($(this).scrollTop()>175){
        // animate fixed div to small size:
        $('.wrapper').stop().animate({ height: 90 },100);
    } else {
        //  animate fixed div to original size
        $('.wrapper').stop().animate({ height: 175 },100);
    }
}); 

Here goes: http://jsfiddle.net/bnsUB/4/

If you want to animate any other thing (such as paddings and margins), just add them as values to the object you pass to the .animate() function. ( for example - { height: 175, 'padding-top': 20, 'margin-top': 10 } etc. )

他のヒント

$(window).scroll(function()
{
    if  ($(window).scrollTop() == $(document).height() - $(window).height())
      {
        $('#tt').animate({height:'90px'}, 500);
      }

});

Here is a solution in vanilla JS and CSS animation:

JS:

window.onscroll = function () {
  scrollFunction()
};

function scrollFunction() {
  if (document.body.scrollTop > 175 || document.documentElement.scrollTop > 175) {
    document.getElementById("header").classList.add("narrow");
  } else {
    document.getElementById("header").classList.remove("narrow");
  }
}

CSS:

#header{
  transition: 0.2s;
  height: 175px;
}
#header.narrow{
  height: 90px !important;
}
#header .anyelementclass{
  transition: 0.2s;
}
#header.narrow .anyelementclass{
  /* any style here */
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top