【问题标题】:Firefox fails to set focus to text areaFirefox 无法将焦点设置到文本区域
【发布时间】:2016-03-22 20:30:10
【问题描述】:

我有一个脚本,我在其中捕获用户粘贴数据,对其进行操作,然后将其插入用户光标所在的同一位置。这是因为粘贴数据是 HTML,用户粘贴的位置必须是 textarea,它只接受纯文本。这是代码:

<textarea autofocus="true" id="editable" name="editable"></textarea>

当用户尝试粘贴一些数据时,我的代码会将粘贴重定向到隐藏的contenteditable div。这会丢失插入符号的位置,因此在切换焦点之前,我将其保存为:

    var storedCaret = textarea.selectionStart;

稍后,在我执行了必要的转换之后,我尝试检索它:

    editable.focus();
    editable.setSelectionRange(storedCaret, storedCaret);
    window.setTimeout(function() {
        document.execCommand("insertHTML", false, formattedText);
    }, 50);

这适用于 Chrome (49.0.2623.87 m)。但令我非常沮丧的是,在 Firefox (43.0.1) 中,粘贴不起作用。根据我的调试,在 execCommand 触发时,textarea#editable 被正确选择为document.activeElement,但粘贴完全失败。

jQuery 是一个可以接受的解决方案,但我不想使用任何其他插件。

【问题讨论】:

    标签: javascript firefox textarea paste execcommand


    【解决方案1】:

    对于处于我这个位置的迷失和困惑的灵魂,这就是我最终的选择:

    if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
            {
                var strLeft = textarea.value.substring(0, currentPos);
                var strRight = textarea.value.substring(currentPos, textarea.value.length);
                textarea.value = strLeft + formattedText + strRight;
            }
    

    它包含在 if 中,因为 insertHTML 在 Chrome 中效果更好。它基本上保存光标位置,然后在字符串中拼接。粗暴但对我的需求有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      相关资源
      最近更新 更多