我有一个固定在页面顶部的div,它可以导航到网站。它的高度为175像素。当您向下滚动页面时,此DIV将保持显示状态。
当用户向下滚动页面175px时,我希望这个div收缩到90px的高度,并在向下滚动页面时保持在90px。当它们向上滚动到顶部时,我希望DIV能长回原来的175像素高度。
我希望在这样做的时候(最好是向上滑动和向下滑动),并且更喜欢使用CSS3来做…
这是我到目前为止的一部分,但因为我是一个多疑的人,不知道如何处理事情…http://jsfiddle.net/bnsUB/
编辑:我忘了提到,我在这个DIV中也有内容,需要在容器上下滑动时调整其填充等。因此,如果这些填充值也可以收缩/增长,那么这将是一个额外的奖励
您需要根据窗口的当前$.scrollTop()
值触发一个操作。
类似于:
$(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);
}
});
下面是:http://jsfiddle.net/bnsUB/4/
如果要对任何其他东西(如填充和边距)设置动画,只需将它们作为值添加到传递给.animate()
函数的对象中即可。(例如-{ height: 175, 'padding-top': 20, 'margin-top': 10 }
等)
$(window).scroll(function()
{
if ($(window).scrollTop() == $(document).height() - $(window).height())
{
$('#tt').animate({height:'90px'}, 500);
}
});
这里有一个香草JS和CSS动画的解决方案:
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 */
}