我有svg文字填充是动态的。一旦用户点击撤消按钮,它必须撤消svg和textarea,一旦用户点击重做按钮,它应该重做svg文本填充和textarea。我有textarea的完成撤消和重做功能,而与SVG元素如何通过jQuery的实现这一如何撤消和重做在SVG元素onclick?
$("#enter-text").on("keypress",function(){
$("#svg_id").html($(this).val());
})
//this value is kept small for testing purposes, you'd probably want to use sth. between 50 and 200
const stackSize = 10;
//left and right define the first and last "index" you can actually navigate to, a frame with maximum stackSize-1 items between them.
//These values are continually growing as you push new states to the stack, so that the index has to be clamped to the actual index in stack by %stackSize.
var stack = Array(stackSize), left=0, right=0, index = 0, timeout;
//push the first state to the stack, usually an empty string, but not necessarily
stack[0] = $("#enter-text").val();
updateButtons();
$("#enter-text").on("keydown keyup change", detachedUpdateText);
$("#undo").on("click", undo);
$("#redo").on("click", redo);
//detach update
function detachedUpdateText(){
clearTimeout(timeout);
timeout = setTimeout(updateText, 500);
}
function updateButtons(){
//disable buttons if the index reaches the respective border of the frame
//write the amount of steps availabe in each direction into the data- count attribute, to be processed by css
$("#undo")
.prop("disabled", index === left)
.attr("data-count", index-left);
$("#redo")
.prop("disabled", index === right)
.attr("data-count", right-index);
//show status
$("#stat").html(JSON.stringify({
left,
right,
index,
"index in stack": index % stackSize,
stack
}, null, 4))
}
function updateText(){
var val = $("#enter-text").val().trimRight();
//skip if nothing really changed
if(val === stack[index % stackSize]) return;
//add value
stack[++index % stackSize] = val;
//clean the undo-part of the stack
while(right > index)
stack[right-- % stackSize] = null;
//update boundaries
right = index;
left = Math.max(left, right+1-stackSize);
updateButtons();
}
function undo(){
if(index > left){
$("#enter-text").val(stack[--index % stackSize]);
updateButtons();
}
}
function redo(){
if(index < right){
$("#enter-text").val(stack[++index % stackSize]);
updateButtons();
}
}
https://jsfiddle.net/yvp3jedr/6/
不知道你是否注意到了我的约撤销/重做最后回复您。第二个答案是我创建了一个类别版本,将撤销 - 重做逻辑分离,以使其更容易一些。 http://stackoverflow.com/questions/39894830/how-to-undo-and-redo-event-in-javascript-with-browser-compatible/39897359#39897359你真正需要知道的关于撤消/重做的唯一的事情,是2件事,我做了什么“做”,以及我需要做些什么来“撤销”(IOW:扭转我刚才做的)。还有什么是你想要做的SVG,因为目前你只是从输入到SVG复制文本。 – Keith
@keith我的撤销重做功能工作正常,但现在textarea值将动态填充到svg元素中。所以撤消也应该为svg做。这是一款t恤定制产品设计。 – Parker
所以我假设你有一个SVG,你的更新,目前你的代码只是用TextArea中的内容替换SVG中的所有内容。 – Keith