【问题标题】:Undo TAB in textarea在 textarea 中撤消 TAB
【发布时间】:2014-03-26 17:34:26
【问题描述】:

当在 textarea 标签中按下TAB 并插入一个\t 字符时,有很多关于如何防止聚焦下一个元素的问题。或任何其他角色。他们都得到了这样的回答:

  1. 捕获 TAB 按键
  2. 获取当前插入符号位置和选择信息
  3. 替换该值,使其包含\t 或用户想要的任何内容。

所有这些都可以正常工作,直到您在TAB 之后按“撤消”或CTRL+Z

如果您这样做,您会遇到一些副作用,具体取决于您使用的浏览器:

  • Firefox 将删除 \t 但插入符号 pos 将转到末尾并选择 textarea 中的所有文本
  • Chrome 不会将此 \t 视为用户输入,因此 CTRL+Z 将撤消上一次操作,将 \t 留在原处,还有一些难以预测的插入符号问题
  • IE 的行为与 Chrome 相同

你可以在这里观看http://jsfiddle.net/c7zc8/1/

问题是如何让它跨浏览器和“可撤销”?

【问题讨论】:

    标签: javascript textarea


    【解决方案1】:

    对于最新的 Chrome (33),以下工作:

    var ta = document.getElementById("textareaId");
    ta.addEventListener("keydown", function(e) {
        if (e.which===9) {
            e.preventDefault();
            document.execCommand("insertText", false, "\t");
        }
    }, false);
    

    参考: Javascript textarea undo redo

    然而,对于 IE,没有完美的解决方案。 IE11 有 ms-beginUndoUnit 和 ms-endUndoUnit,但根据 Tim Down 在 internet explorer alternative to document.execCommand("insertText",...), for text insertion that can be undone/redone by the user

    【讨论】:

    猜你喜欢
    • 2011-11-25
    • 1970-01-01
    • 2012-08-02
    • 2021-06-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 2012-10-03
    • 2011-01-01
    相关资源
    最近更新 更多