js操作撤销反撤销

  • Post author:
  • Post category:其他


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
    <TITLE> test command </TITLE>
    <META NAME="Author" CONTENT="emu">

    <SCRIPT LANGUAGE="JavaScript">
        <!--
        var actionStack = [];//操作栈
        var actionIndex = 0;//操作栈中当前操作的指针

        //-----------------------  command对象基类 ------------------------------
        function BaseAction(){
        }
        BaseAction.prototype.exec=function(){
            actionStack[actionIndex++] = this;
            actionStack.length = actionIndex;
        }
        BaseAction.prototype.undo=function(){
            alert("此操作未定义相应的undo操作");
        }
        BaseAction.prototype.redo=function(){
            alert("此操作未定义相应的redo操作");
        }

        //-----------------------  change操作的command对象 ------------------------------
        function ChangeAction(elm){
            this.sourceElement = elm;
            this.oldValue = elm.defaultValue;
            this.newValue = elm.value;
            elm.defaultValue = elm.value;
            this.status = "done";
        }
        ChangeAction.prototype = new BaseAction();
        ChangeAction.prototype.undo = function(){
            if (this.status != "done") return;
            this.sourceElement.value = this.sourceElement.defaultValue = this.oldValue;
            this.status = "undone";
        }

        ChangeAction.prototype.redo = function(){
            if (this.status != "undone") return;
            this.sourceElement.value = this.newValue;
            this.status = "done";
        }


        //---------------------  全局函数  ----------------------------
        function undo(){
            if (actionIndex>0){
                actionStack[--actionIndex].undo();
            }
        }
        function redo(){
            if (actionIndex<actionStack.length){
                actionStack[actionIndex++].redo();
            }
        }

        function changeValue(event){
            event = (event) ? event:window.event;
            new ChangeAction(event.srcElement || event.target).exec();
        }
        //-->
    </SCRIPT>
</HEAD>

<BODY oncontextmenu="return false">
<input type=button onclick=undo() value=undo>
<input type=button onclick=redo() value=redo>
<input value="drag me"  onchange="changeValue(event)" style="position:absolute;left:150px;color:blue">
<input value="drag me"  onchange="changeValue(event)" style="position:absolute;left:350px;color:green">
<input value="drag me"  onchange="changeValue(event)" style="position:absolute;left:550px;color:violet">
</BODY>
</HTML>



版权声明:本文为o11111123456l原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。