使用原生的javascript封装动画函数(有callback功能)

复制代码
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        #box {
            width: 100px;
            height: 100px;
            background-color: greenyellow;
            position: absolute;
        }
    </style>
</head>
<body>
<input type="button" value="按钮" id="btn"/>

<div id="box"></div>
<script>
    var btn = document.getElementById("btn");
    btn.onclick = function () {
        animate(box, {"height": 400, "width": 400, "borderRadius": 150, "left": 100, "top": 100}, function () {
            animate(box, {"height": 200, "width": 100, "borderRadius": 20, "left": 200, "top": 50}, function () {
                animate(box, {"height": 100, "width": 200, "borderRadius": 100, "left": 400, "top": 400})
            })
        })
    }
    function animate(obj, json, fn) {
        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
            var isTrue = true;
            for (var k in json) {//{k:json[k]}
                var leader = parseInt(getAttr(obj, k)) || 0;//如果是nan的话,给一个默认值
                var step = (json[k] - leader) / 10;
                step = step > 0 ? Math.ceil(step) : Math.floor(step);//做一个判断,当step>0的时候,向上取整,保证至少为一;<0的时候,向下取整,保证至少为-1
                leader = leader + step;
                obj.style[k] = leader + "px";
                console.log("代码还在执行");
                if (leader != json[k]) {
                    isTrue = false;
                }
            }
            if (isTrue) {
                clearInterval(obj.timer);
                if (fn) {
                    fn();
                }
            }
        }, 15);
    }
    function getAttr(demo, attr) {
        if (window.getComputedStyle) {
            return window.getComputedStyle(demo, null)[attr];
        } else {
            return demo.currentStyle[attr];
        }
    }
</script>
</body>
</html>
复制代码

 

posted @   笠航  阅读(178)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示