首页 > javascript,alert阻塞和jquery动画问题。

javascript,alert阻塞和jquery动画问题。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <style>
        .box {
            width: 1000px;
            height: 500px;
            background-color: #ccc;
        }
    </style>
</head>
<body>
    <div class="box"></div>
    分别在点击按钮后一秒、两秒、三秒点确定方可查看不同。<br>
    <button>动画</button>
    <script>
        $('button').on('click', function () {
            $('.box').hide(3000);
            alert('弹出窗口后动画不进行,但是关掉窗口后,会直接跳到原本动画应该到的地方');
        });
    </script>
</body>
</html>
var i = 0;
setInterval(function () {
    console.log(++i)
},1000);
alert(1);

上面是demo,
alert堵塞页面js进行,但是为什么不会堵塞动画进行?动画虽然看不到,但是它真的默默的做了。


因为它阻塞的是后面的代码啊, 你先执行的代码当然不会阻塞.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <style>
        .box {
            width: 1000px;
            height: 500px;
            background-color: #ccc;
        }
    </style>
</head>
<body>
    <div class="box"></div>
    分别在点击按钮后一秒、两秒、三秒点确定方可查看不同。<br>
    <button>动画</button>
    <script>
        $('button').on('click', function () {
            alert('弹出窗口后动画不进行,但是关掉窗口后才开始动画');
            $('.box').hide(3000);
        });
    </script>
</body>
</html>

alert()后面的js代码不会执行,但动画是在alert前面,已经开始工作了,
alert后,页面失去焦点,页面不更新渲染结果(只是不更新结果,实际在运行),点击确认后更新此刻的动画效果。

以上部分为猜测,没测试,加上是业余爱好者,说错了不要踩我哈。


jquery动画是通过timer来计算的,alert会暂停界面的刷新,但是alert结束后,timer会根据当前时间计算动画应该进行到哪个步骤了。细节可以参考jquery代码:

javascriptfunction Animation( elem, properties, options ) {
    //...
    jQuery.fx.timer(
        jQuery.extend( tick, {
            elem: elem,
            anim: animation,
            queue: animation.opts.queue
        })
    );
}
【热门文章】
【热门文章】