第157题 JS设计并实现撤销重做功能
分析
- 维护一个
list和index input change时push到list且index++Undo时index-1,redo时index+1
<div>
<input id="input-text" />
<button id="undo">undo</button>
<button id="redo">redo</button>
</div>
<script>
const inputText = document.getElementById("input-text")
const undo = document.getElementById("undo")
const redo = document.getElementById("redo")
const list = [inputText.value] // 初始化列表
const currIndex = list.length - 1 // 初始化index
inputText.addEventListener('change', e=>{
const text = e.target.value
list.length = currIndex + 1 // 截取掉index后面的部分
list.push(text)
currIndex++ // index增加
})
undo.addEventListener('click',()=>{
if(currIndex <= 0) return
currIndex-- // index减少
inputText.value = list[currIndex]
})
redo.addEventListener('click',()=>{
if(currIndex >= list.length - 1) return
currIndex++ // index增加
inputText.value = list[currIndex]
})
</script>
