如何实现撤销功能?js可以吗?

czp3158 2009-11-12 05:37:14
如题
...全文
420 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
dh20156 2009-11-13
  • 打赏
  • 举报
回复
当然可以,参见:

Command模式-命令模式
czp3158 2009-11-13
  • 打赏
  • 举报
回复
怎么没人知道吗????
dh20156 2009-11-13
  • 打赏
  • 举报
回复
简单写个参考的:


<style type="text/css">
div{border:3px solid black;padding:10px;}
</style>

<div id="x">初始值</div>

<script type="text/javascript">
//要应用command模式的对象
var box = function(dbox,svalue){
this.value = svalue;
this.dbox = dbox;
this.restart = function(){//约定一个回到初始状态的方法
this.value = svalue;
this.dbox.innerHTML = svalue;
};
};
box.prototype = {
setValue:function(svalue){
this.value = svalue;
this.dbox.innerHTML = svalue;
}
};
//command对象
var command = function(receiver){
this.receiver = receiver;
this.log = [];
this.un_re_do = -1;
};
command.prototype = {
query:function(cmd){
if(!cmd||cmd.constructor!=Function){return;}
var args = Array.prototype.slice.call(arguments,0);
var idx = this.un_re_do+1,ll = this.log.length;
if(ll){this.log.splice(idx,ll-idx);}
this.log.push(args);
this.un_re_do++;
this.exec.apply(this,args);
},
exec:function(){
var args = Array.prototype.slice.call(arguments,0);
if(!args.length){return;}
var cmd = args.shift();
if(cmd.constructor!=Function){return;}
cmd.apply(this.receiver,args);
},
undo:function(){
var idx = (this.un_re_do>=0)?--this.un_re_do:-1;
this.unredo(idx);
},
redo:function(){
var idx = (this.un_re_do<this.log.length-1)?++this.un_re_do:this.un_re_do;
this.unredo(idx);
},
unredo:function(idx){
if(idx>=0){
var cmd_step = this.log[idx];
this.exec.apply(this,cmd_step);
}else{
this.receiver.restart();
}
}
};

var hellobox = new box(document.getElementById('x'),'初始值');
var boxCommand = new command(hellobox);

window.setTimeout(function(){boxCommand.query(hellobox.setValue,'第一次修改值!');},1000);
window.setTimeout(function(){boxCommand.undo();},2000);
window.setTimeout(function(){boxCommand.query(hellobox.setValue,'第二次修改值!');},3000);
window.setTimeout(function(){boxCommand.undo();},4000);
window.setTimeout(function(){boxCommand.redo();},5000);
window.setTimeout(function(){boxCommand.query(hellobox.setValue,'第三次修改值!');},6000);
window.setTimeout(function(){boxCommand.query(hellobox.setValue,'第四次修改值!');},7000);
window.setTimeout(function(){boxCommand.undo();},8000);
window.setTimeout(function(){boxCommand.undo();},9000);
window.setTimeout(function(){boxCommand.undo();},10000);
</script>

87,993

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧