87,910
社区成员
发帖
与我相关
我的任务
分享
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Undo Redo</title>
<script src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
<style type="text/css">
body{margin:0;padding:0;font-family:Microsoft YaHei;}
.click{width:80px;height:20px;line-height:20px;margin-left:10px;float:left;text-align:center;border:#bbb solid 1px;background-color:#f5f5f5;cursor:pointer;}
</style>
</head>
<body>
<br/><br/><br/>
<div style='width:400px;height:400px;margin:0 auto;'>
<textarea id='tt' maxlength='100' style='width:390px;height:100px;'></textarea>
<div style='width:400px;font-size:14px;color:#e00;text-align:center;'>(*限字母和数字,keyup对汉字效果不好)</div>
<div style='width:400px;height:20px;margin-top:20px;margin-left:200px;'>
<div id="tundo" class='click'>undo</div>
<div id="tredo" class='click'>redo</div>
</div>
</div>
<script language="javascript">
var ud = new UndoRedo(100);
$(".click").each(function(){
$(this).click(function(){
switch($(this).prop("id")){
case "tundo":
var t = ud.undo();
if(t != null){
$("#tt").val(t);
}
break;
case "tredo":
var t = ud.redo();
if(t != null){
$("#tt").val(t);
}
break;
}
});
});
$("document").ready(function(){
$("#tt")[0].value = "";
ud.do("");
$("#tt").keyup(function(){
var t = $("#tt").val();
if(t != null && t != undefined){
ud.do(t);
}
});
});
function UndoRedo(size)
{
var s = size;
var l = 0;//obj count
var pos = -1;//current data
var a = new Array(l);
for(var i=0;i<s;++i){
a[i] = null;
}
this.do = function(obj)
{
if(pos == l-1){//指针在数据未尾
if(l == s){//如数组已满则清除掉最旧的数据
for(var i=0;i<s-1;++i){
a[i] = a[i+1];
}
a[s-1] = obj;
}
else{
a[pos+1] = obj;
pos +=1;
l++;
}
}
else{//指针不在数据未尾
if(pos >= 0){
a[pos+1] = obj;
for(var i=pos+2;i<s;++i){
a[i] = null;
}
l = pos + 2;
pos+=1;
}
else{
a[0] = obj;
l=1;
pos = 0;
}
}
}
//返回上一个数据,但不移动标志
this.prev = function()
{
if(pos > 0){
return a[pos-1];
}
return null;
}
//返回当前数据
this.now = function()
{
if(pos >=0 && pos < l){
return a[pos];
}
return null;
}
//返回上一个数据
this.undo = function(state)
{
if(state == true){
return pos > 0 ? true : false;
}
else{
if(pos > 0){
var re = a[pos-1];
pos-= 1;
return re;
}
else{
return null;
}
}
}
//返回下一个数据
this.redo = function(state)
{
if(state == true){
return (pos < l-1) ? true : false;
}
else{
if(l > 0){
if(pos < l-1){
var obj = a[pos + 1];
pos += 1;
return obj;
}
else{
return null;
}
}
else{
return null;
}
}
}
}
</script>
</body>
</html>