前端开发函数封装与回调函数的使用基础例子

web前端工程师开发工具
前端开发和嵌入式开发工具
前端开发工具实时预览设计

html 代码

<!DOCTYPE html>
    <head>
        <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
        <title>无标题文档</title>
        <style>
            #div1 {
                width: 100px;
                height: 100px;
                background: red;
                position: absolute;
                top: 50px;
                left: 30px;
            }
        </style>
    </head>
    <body>
        <input id=”btn1″ type=”button” value=”back” />
        <input id=”btn2″ type=”button” value=”go” />
        <div id=”div1″></div>
        <script>
            var oBtn1 = document.getElementById(‘btn1’)
            var oBtn2 = document.getElementById(‘btn2’)
            var oStop = document.getElementById(‘stop’)
            var oDiv = document.getElementById(‘div1’)
            oBtn1.onclick = function() {
                doMove(oDiv, ‘left’, 10, 12, function() {
                    doMove(oDiv, ‘top’, 100, 12)
                })
            }
            oBtn2.onclick = function() {
                doMove(oDiv, ‘left’, 800, 12, function() {
                    doMove(oDiv, ‘top’, 10, 12)
                })
            }
            function doMove(obj, attr, target, dir, Endfn) {
                dir = parseInt(getStyle(obj, attr)) < target ? dir : -dir
                clearInterval(oDiv.timer)
                oDiv.timer = setInterval(function() {
                    var speed = parseInt(getStyle(obj, attr)) + dir
                    if (
                        (speed < target && dir < 0) ||
                        (speed > target && dir > 0)
                    ) {
                        speed = target
                    }
                    oDiv.style[attr] = speed + ‘px’
                    if (speed == target) {
                        clearInterval(oDiv.timer)
                        Endfn && Endfn()
                    }
                }, 30)
            }
            function getStyle(obj, attr) {
                return obj.currentStyle
                    ? obj.currentStyle[attr]
                    : getComputedStyle(obj)[attr]
            }
        </script>
    </body>
</html>
macbook 前端开发工具
好的web前端开发工具
高效web前端开发工具
» 本文来自:前端开发者 » 《前端开发函数封装与回调函数的使用基础例子》
» 本文链接地址:https://www.rokub.com/8115.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!