javascript && jquery 延时屏幕滚动元素fadeout效果,允许打断。

这个问题,我纠结了一两天,起初,我用的是原生的javascript代码(原谅我没保留代码),写完之后发现乍一看没问题,但是当快速滚动时,即多次调用了,这个时候必须把之前的函数animation 给clear掉。而延时,之前省事,就用delay方法(jquery方法),后来发现不停快速滚动的时候还是有BUG。百思不得其解,animation动画已经clear了,怎么还会有BUG(快速滚动一闪一闪)?code如下:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>导航条</title>
    <style>
        body{
            padding:0;
            margin:0;
        }
        #nav{
            width:100%;
            min-height: 45px;
            background: #337ab7;
            position: fixed;
        }

    </style>
</head>
<body style="height:2000px;">
<nav id="nav">菜单栏</nav>
<script src="jquery-1.11.2.min.js" type="text/javascript"></script>
<script>
    $(function () {
        $('body').on('<span style="font-family: Arial, Helvetica, sans-serif;">scroll</span>', function(event) {

            $("#nav").stop(true,true).show();
            $("#nav").delay(2000).fadeOut(1000,function(){
                
            });
        });
    });
</script>
</body>
</html>


鼠标不停的滚动(间隔小于2S)就会发现bug,后来,经过大婶提点,原来,不仅仅fadeout 等animation放入了队列,delay也是有可能放入了队列的,于是乎,在jquery官网上查询一番,果不其然:

Description: Set a timer to delay execution of subsequent items in the queue.


然而,怎么clear队列呢?往下看,有新发现:

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

原来clear不掉,但是没关系,可以用原生的settimeout来作延时器:


$(function(){
        var timer = null;

        var timerStart = function(){
            window.clearTimeout(timer);
            timer = null;
            $('#nav').show();
            timer = window.setTimeout(function(){
                $('#nav').fadeOut();
            }, 2000);
        }

        $(window).on('scroll', function(event) {
            timerStart();
        });
    });

至此,大功告成,不再有BUG了。


明白一个很深刻的道理,要像大婶学习!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值