javascript实现的拖拽回放

这个功能很简单,直接贴代码啊:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
#div1 {width:100px; height:100px; background:red; position:absolute;}
#btn1 {position:absolute; right:10px; top:10px; width:50px;}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>拖拽回放</title>
<script>
window.onload = function () {
    var oDiv = document.getElementById('div1');
    var oBtn = document.getElementById('btn1');
    var arr = [];
    
    oDiv.onmousedown = function (ev) {
        var oEvent = ev || event;
        
        var disX = oEvent.clientX - oDiv.offsetLeft;
        var disY = oEvent.clientY - oDiv.offsetTop;
        
        document.onmousemove = function (ev) {
            var oEvent = ev || event;
            var l = oEvent.clientX - disX;
            var t = oEvent.clientY - disY;
            
            arr.push({x: l, y: t});
            
            oDiv.style.left = l + 'px';
            oDiv.style.top = t + 'px';
        };
        document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup = null;
        };
    };    
    oBtn.onclick = function () {
        var timer = setInterval (function () {
            if(arr.length > 0) {
                var oData = arr.pop();    
                oDiv.style.left = oData.x + 'px';
                oDiv.style.top=oData.y + 'px';
            } else {
                clearInterval(timer);
            }
        }, 10);
    };
};
</script>
</head>
<body>
<input id="btn1" type="button" value="回放" />
<div id="div1">
</div>
</body>
</html>
posted @ 2013-08-09 11:16  breezefeng  阅读(463)  评论(0编辑  收藏  举报