简体   繁体   English

Firefox可以在textarea中使用document.execCommand吗?

[英]Can Firefox use document.execCommand in a textarea?

With the cursor in a contenteditable div , both Chrome and Firefox can emulate typing "sometext" like this: 将光标放在一个可信的div ,Chrome和Firefox都可以模拟输入“sometext”,如下所示:

document.execCommand('insertText', false, 'sometext');

In Chrome, this works when you're in a textarea as well. 在Chrome中,当你在textarea时,这也适用。 In Firefox, I get the error "NS_ERROR_FAILURE:". 在Firefox中,我收到错误“NS_ERROR_FAILURE:”。

Here's a fiddle to demonstrate: http://jsfiddle.net/ukx37/ . 这是一个小提琴演示: http//jsfiddle.net/ukx37/ In Chrome, hit enter and you type "ENTER\\n". 在Chrome中,按Enter键,然后输入“ENTER \\ n”。 In Firefox, you type "\\n" and get an error NS_ERROR_FAILURE. 在Firefox中,键入“\\ n”并收到错误NS_ERROR_FAILURE。

Does anybody know if there's a way to get this working in Firefox? 有没有人知道是否有办法在Firefox中使用它? Or, if not, is there some way I can test for support without a try-catch statement? 或者,如果没有,是否有一些方法可以在没有try-catch语句的情况下测试支持?

Also, I don't want to manually edit the textarea's value because doing so breaks the edit history. 此外,我不想手动编辑textarea的值,因为这样做会破坏编辑历史记录。

Figured out that the error is being fired because the focused Node isn't contentEditable. 弄清楚错误是由于焦点Node不是contentEditable而被触发的。 If you make the textarea contentEditable it stops firing errors, but gets all buggy. 如果你使textarea contentEditable,它会停止触发错误,但会得到所有错误。 Firefox will sometimes put the inserted text in the textarea, sometimes put it in the DOM as a child node of the textarea (and never display it), sometimes do nothing. Firefox有时会将插入的文本放在textarea中,有时将它作为textarea的子节点放在DOM中(并且永远不会显示它),有时什么都不做。 No errors are fired, but it's still unusable. 没有错误被触发,但它仍然无法使用。 Same thing for making a parent contentEditable and the textarea not. 使父contentEditable和textarea不相同。

The answer I'm using for now is feature-detecting and giving up if it doesn't "just work". 我现在使用的答案是功能检测,如果它不“正常工作”就会放弃。 If somebody gets Firefox to work I'll un-accept this and accept theirs. 如果有人让Firefox上班,我会不接受这个并接受他们的。 Until then, here's the code I'm using. 在那之前,这是我正在使用的代码。

var canEditInput = (function () {
    try {
        var t = document.createElement('textarea');
        document.body.appendChild(t);
        t.focus();
        document.execCommand('insertText', false, 'x');
        document.body.removeChild(t);
        return t.value === 'x';
    } catch (e) {
        return false;
    }
})();

Note that we can't give t display:none; 请注意,我们不能给t display:none; because then it can't be focused. 因为那时它无法集中注意力。 But it shouldn't matter, because the JS should finish (and remove t ) before the browser starts to draw the next frame. 但它应该没关系,因为JS应该在浏览器开始绘制下一帧之前完成(并删除t )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM