在iframe的光标位置插入HTML控件

Inserting HTML controls at cursor position in iframe

本文关键字:插入 HTML 控件 位置 光标 iframe      更新时间:2023-09-26

我正在开发一个文本编辑器,允许用户在文档中输入HTML文本框。例如,如果用户写"Hello world",在"Hello"answers"world"之间放置插入符号并单击文本框按钮,我需要在当前插入符号位置放置文本框控件。这可能吗?

目前,我可以将文本框放在末尾,这很简单,因为我只是在JavaScript中创建了一个文本框,并将其附加到<body>元素。我不知道的是我们如何把HTML控件放在字符串之间。

我们可以通过使用execCommand('insertHTML',..)在光标位置插入文本,但是我们可以用它来插入HTML标签吗?下面是我想要实现的HTML代码:

:

<iframe>
..
<body>
"hello world"
</body>
</iframe>

点击文本框按钮后,它应该是这样的:

    <iframe>
    ..
    <body>
    "hello <input type"text" /> world" //NOTE: this wont work as it will just print it with the tags nad nt exec it
    </body>
    </iframe>

您可以在IE中使用document.execCommand("InsertInputText"),在其他浏览器中使用document.execCommand("InsertHTML")

实时演示:http://jsfiddle.net/DymzW/

代码:

if (!document.execCommand("InsertInputText", false, '')) {
    document.execCommand("InsertHTML", false, '<input type="text">');
}