新手求助,scroll事件里加if else语句animate动画不能正常显示的问题

qq_33383606 2017-04-06 08:31:56
<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,高度又变回去。
...全文
221 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_33383606 2017-04-07
  • 打赏
  • 举报
回复
解决了,谢谢楼上~
  • 打赏
  • 举报
回复
要停止之前的动画,要不没滚动一次就压入一个动画,滚动到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);
    });

87,989

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧