关于jquery 动画 animate问题

查看:159
本文介绍了关于jquery 动画 animate问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<!DOCTYPE html>
<html>
<head>

<style>
    *{
        margin: 0;
        padding: 0;
    }
    .result{
        width: 100%;
        height: 50px;
        background: #ccc;
        position: fixed;
        top: -50px;
    }
    .result.active{
        top: 0;
    }
</style>

<script src="js/jquery-1.11.3.min.js"></script>

</head>


<body style="height:4500px;">

<div class="result"></div>


<script>

$(function(){
    var fs = true;
    $(window).scroll(function(event) {
        
        if( $(window).scrollTop() > 50 ){
            
            if(fs){
                
                $(".result").stop().animate({
                    top: 0
                },300);

                fs = false;
            }
        }
        else{

            $(".result").stop().animate({
                top: "-50px"
            },300);

            fs = true;
        }
    });
 });
</script>

</body>
</html>

实现效果:想实现滚动条位置大于指定值出现滚动横条。小于则隐藏。
出现问题:滚动到指定位置以后,动画很慢进入,小于指定值也会很慢收回。这是为什么?

解决方案

scroll 的触发效率是很高的,一次滚动可能就触发了100次,你在写判断$(window).scrollTop()>50,未进行节流的控制,导致触发了多次的$(".result").animate(),建议在使用scroll(),尽量内部定义节流阀函数,提高性能.

简单的实现

$(function(){
    //fs的作用域需高于scroll内部
    var fs = true;
    $(window).scroll(function(event) {    
        if( $(window).scrollTop() > 50 ){ 
            if(fs){   
                $(".result").stop().animate({
                    top: 0
                },300,function(){
                  //animate里的回调函数
                  fs = false;
                });
               
            }
        }
        else{
            $(".result").stop().animate({
                top: "-50px"
            },300,function(){
                fs = true;
            });
           
        }
    });
 });

高级实现

函数防抖与节流

这篇关于关于jquery 动画 animate问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆