简单清晰的缓冲运动框架

TestMove.js

View Code
function getStyle(obj, attr) {
    if (obj.currentStyle) {
        return obj.currentStyle[attr];
    }
    else {
        return getComputedStyle(obj, false)[attr];
    }
}

function startMove(obj, json, fn) {
    clearInterval(obj.timer);
    obj.timer = setInterval(function () {
        var bStop = true; //停止运动的标记
        for (var attr in json) {
            var iCurr = 0;
            //获取当前的值
            if (attr == 'opacity') {
                iCurr = parseInt(Math.round(parseFloat(getStyle(obj, attr)) * 100));
            }
            else {
                iCurr = parseInt(getStyle(obj, attr));
            }
            //计算速度
            var iSpeed = (json[attr] - iCurr) / 8;
            iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);

            //检测是否停止
            if (iCurr != json[attr]) {
                bStop = false;
            }

            //设置属性
            if (attr == 'opacity') {
                obj.style.filter = 'alpha(opacity:' + iCurr + iSpeed + ')';
                obj.style.opacity = (iCurr + iSpeed) / 100;
            }
            else {
                obj.style[attr] = iCurr + iSpeed + 'px';
            }
        }
        if (bStop) {
            clearInterval(obj.timer);
            if (fn) {
                fn();
            }
        }
    }, 30);
}

TestMove.html

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApplication5.WebForm3" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7     <title></title>
 8     <style type="text/css">
 9         #test
10         {
11             width:100px;
12             height:100px;
13             border:1px solid black;
14             position:absolute;
15             left:0;
16         }
17     </style>
18     <script src="TestMove.js" type="text/javascript"></script>
19     <script type="text/javascript">
20         window.onload = function () {
21             startMove(document.getElementById('test'), { 300,height:300,left:500})
22         }
23     </script>
24 </head>
25 <body>
26     <form id="form1" runat="server">
27     <div id="test">
28     
29     </div>
30     </form>
31 </body>
32 </html>
原文地址:https://www.cnblogs.com/fumj/p/2731287.html