我在页面上有一个很小的contenteditable
范围。在某些情况下(例如,按退出键),我想以编程方式取消编辑模式。
有办法吗?
到目前为止,我仅发现了删除contenteditable attr并在此后不久(例如,大约100毫秒后)恢复它的方法,这可能不是正确的方法:-(我想我可以将焦点更改为同样的效果。
我真正想要的是elem.endEdit()
或类似的东西...
谢谢!
您可以在正在编辑的元素上调用blur()。这是一个示例:https://codepen.io/MarcMouries/pen/PowEYRv
<h3>Editable content</h3>
<div contenteditable="true" id="editor">Click me, type something, then press the ESC key</div>
<h3>Events</h3>
<textarea id="log" rows="10" cols="100" readonly></textarea>
var element = document.getElementById("editor");
var eventsLog = document.getElementById("log");
var oldValue = "";
document.addEventListener('keyup', (e) => {
if (event.keyCode == 27) {
eventsLog.value += "ESC key pressed => UNDO reset to (" + oldValue + ")\n";
var element = event.target;
element.textContent = oldValue;
element.blur();
}
}, false);
element.addEventListener("focus", function(event) {
var element = event.target;
oldValue = element.textContent;
eventsLog.value += "FOCUS: value = " + oldValue + "\n";
});
element.addEventListener("blur", function(event) {
var element = event.target;
var newValue = element.textContent;
if(newValue != oldValue) {
eventsLog.value += "Input changed value to: " + newValue + " \n";
}
}, false);