在contenteditable div中收听撤消/重做事件 [英] Listen to undo/redo event in contenteditable div

查看:497
本文介绍了在contenteditable div中收听撤消/重做事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以监听用户可在内容可编辑的div上触发撤消的所有方式?例如,当用户点击Control + Z时,右键单击->撤消,或在文件菜单中编辑->撤消。

Is there a way to listen on all the ways a user could trigger an undo on a contenteditable div? For example when the user hits Control+Z, Right-click -> Undo, or in the file menu Edit -> Undo.

我不是在寻找undo /重做算法或实现,只是具有侦听事件并覆盖行为的能力。

I'm not looking for undo/redo algorithms or implementations, just the ability to listen to the event and overwrite the behavior.

推荐答案

您可以获得<$ c $ input 事件的c> event.inputType 。检查 historyUndo / historyRedo

You can get event.inputType of input event. Check for "historyUndo" / "historyRedo":

var div = document.getElementById("mydiv");
div.addEventListener("input", function(e) {
  switch(e.inputType){
    case "historyUndo": alert("You did undo"); break;
    case "historyRedo": alert("You did redo"); break;
  }
});

<div id="mydiv" contenteditable="true">Hello world!</div>

在最近的浏览器中,您可以使用 beforeinput 事件来取消该事件(尚未在Firefox中)

In recent browsers, you can cancel the event using the beforeinput event (not in Firefox yet):

var div = document.getElementById("mydiv");
div.addEventListener("beforeinput", function(e) {
  switch(e.inputType){
    case "historyUndo": e.preventDefault(); alert("Undo has been canceled"); break;
    case "historyRedo": e.preventDefault(); alert("Redo has been canceled"); break;
  }
});

<div id="mydiv" contenteditable="true">Hello world!</div>

参考文献:

  • InputEvent specification and other inputType values: https://w3c.github.io/input-events/#interface-InputEvent-Attributes
  • Browser compatibility for beforeinput: https://caniuse.com/#feat=mdn-api_htmlelement_beforeinput_event

这篇关于在contenteditable div中收听撤消/重做事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆