美文网首页
关于jQuery animate()的一个小"BUG&

关于jQuery animate()的一个小"BUG&

作者: DHFE | 来源:发表于2018-08-07 22:04 被阅读36次
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <style>
        body {
            position: relative;
        }
        .test {
            position: absolute;
            width: 200px;
            height: 200px;
            margin-top: 300px;
            left: 300px;
            background-color: red;
    
            transition: all 1.5s;
        }
        .line {
            width: 1300px;
            height: 2px;
            background-color: black;
        }
    </style>
    <body>
        <div class="test"></div>
        <div class="line">1300px</div>
        <script>
            $(".test").click(function() {
                animate();
            })
            
            function animate() {
                $(".test").animate({
                    left: "+=" + 800 
                },100,"swing",function() {
                    $("body").append("<h1>H</h1>")
                })
            }
        </script>
    </body>
    </html>
    
    初始状态

    一个简单动画,点击红色方块时,向右移动(CSS动画),当动画执行完成后,页面会出现一个h1标签的H。

    嗯,很直观的动画,但是执行起来就不是这样了。

    某一帧
    这是动画执行到其中某一帧时截取的图片,可以看到,动画未执行完成,h1标签就已经出现了,why?!

    相信大部分同学已经知道咋回事了,对的,jQuery animate()方法和CSS里的transition发生了冲突,其实也不能叫冲突。

    首先要理解浏览器的动画是怎么产生的,由谁负责。

    CSS3动画原理

    其实可能和原理关系也不大,但是知道总好些嘛。

    所以现在问题集中是:同时设置了jQuery animate()方法和CSS3动画属性后,页面动画所带来的表现不一致问题。

    经过对比,这个动画混乱和CSS的内联或者外链无关,只要都存在就会有冲突。

    值得注意的地方:

            // css: transition: all 10s;
    
            $(".test").click(function() {
                animate();
            })
    
            function animate() {
                console.time();
                $(".test").animate({
                    left: "+=" + 800 
                },4000,"linear",function() {
                    $("body").append("<h1>" + $(".test").css("left") + "</h1>");
                    console.timeEnd();
                })
            }
    

    transitiontime参数调整至10sanimate()方法中的参数为4s

    执行中某帧

    执行后,整个动画耗时14s,并且由图可知是animate()方法的动画先执行。

    • 动画耗时总长 = animate()中time + transition中time
    • animate()方法总是先执行,但不会走完全程,由图知,4s后,只移动了350px左右

    那么,大致可以知道,transition的设置影响了animate()方法的执行,更像是animate()被”稀释“了,transition的time设置越长,animate()阶段移动的距离越小。

    当然,还有一个线索。

    4s帧

    animate()执行结束后的瞬间截图,注意到标签上的left值吗?已经是1100px了。
    也就是说,在animate()阶段,元素的CSS值就已设置为正确的值,只是动画并没有走完这个值。

    可是我依旧不知道结果,我只能大慨知道,transitionanimate()阶段的动画产生了影响,这个影响使得animate()方法没有正确的执行完整动画(但是值正确)。


    先这样,有大神看到忘告解~。

    相关文章

      网友评论

          本文标题:关于jQuery animate()的一个小"BUG&

          本文链接:https://www.haomeiwen.com/subject/wconvftx.html