<div class="topbar">
</div>
.topbar{ width: 100%;height:30px;background-color: black;;position: fixed;z-index: 102;}

<script type="text/javascript">
$(document).scroll(function() {
var t=$(document).scrollTop();
if( t>=50){
$(".topbar").animate({height:"50px"},400);
}
else{
$(".topbar").animate({height:"30px"},400);
}
});
</script>
如果把else注释掉的话是可以的,不知道哪里出了问题,求大神帮忙看下。
我的需求是,当滚轮滑到50px时,盒子的高度慢慢变成50,小于50px,高度又变回去。

解决方案 »

  1.   

    要停止之前的动画,要不没滚动一次就压入一个动画,滚动到50之前可能有n个动画要执行了,超过50才又生成n个动画,和之前的-动画相互抵消了    $(document).scroll(function () {
            var t = $(document).scrollTop();
            console.log(t)
            if (t >= 50) {
                $(".topbar").stop().animate({ height: "50px" }, 400);
            }
            else {
                $(".topbar").stop().animate({ height: "30px" }, 400);
            }
        });或者用计时器来延时执行提高效率,也不需要stop
        var timer
        $(document).scroll(function () {
            clearTimeout(timer)
            timer = setTimeout(function () {
                var t = $(document).scrollTop();
                console.log(t)
                if (t >= 50) {
                    $(".topbar").animate({ height: "50px" }, 400);
                }
                else {
                    $(".topbar").animate({ height: "30px" }, 400);
                }
            }, 100);
        });