简体   繁体   English

IE中的document.execCommand问题

[英]Issue with document.execCommand in IE

I am using a html editor and wanted to extend feature to insert html controls at cursor position. 我正在使用html编辑器,并希望扩展功能以在光标位置插入html控件。

The code i am using is: 我使用的代码是:

document.execCommand("insertHTML", false, "<input type=\"text\">") 

This code works fine Chrome and FF but have issue in IE. 这段代码在Chrome和FF上正常运行,但在IE中有问题。 It simply doesn't work and throws "invalid argument" error. 它根本不起作用,并引发“无效参数”错误。 I have tried the following code: 我尝试了以下代码:

if (document.selection && document.selection.createRange) {
     range = document.selection.createRange();
     range.collapse(false);
     range.pasteHTML(value);
}

but the textbox add to top of the document and not inside the html editor. 但文本框会添加到文档顶部,而不是html编辑器内部。

I need help on this. 我需要帮助。 Thanks in advance. 提前致谢。

It looks like you're mixing and matching IE and Modern browser standards in that method. 看起来您正在用这种方法混合并匹配IE和Modern浏览器标准。 I'm not sure it works the way you think it does. 我不确定它是否按照您的想法工作。 Try a little console.log() for firefox or alert() to see which browsers actually enter that method :) 尝试使用一点console.log()来查看firefox或alert(),看看哪些浏览器实际输入了该方法:)

There is no document.selection in Firefox. Firefox中没有document.selection。 It's window.getSelection() instead: 它是window.getSelection():

Try playing around with the following. 尝试使用以下方法。 Should work in both browsers 在两种浏览器中均应工作

if (document.createRange) { // "Standards" :)
    var selection = window.getSelection();

    if (selection.rangeCount > 0) {
        selRange = selection.getRangeAt(0);
        var node = document.createTextNode(stringValue);
        selRange.insertNode(node);
        selRange.setStartAfter(node);
        selection.removeAllRanges();
        selection.addRange(selRange);
    }

} else if (document.selection) { // fallback for IE6-8
    selRange = document.selection.createRange();

    selRange.select();
    selRange.pasteHTML(stringValue);
}

If you encapsulate that in a method and pass "stringValue" you can insert text anywhere. 如果将其封装在方法中并传递“ stringValue”,则可以在任何位置插入文本。

Hope that helps! 希望有帮助!

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

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