gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 22:45:29 25 4
gpt4 key购买 nike

我正在开发一个允许用户在文档中输入 HTML 文本框的文本编辑器。例如,如果用户输入“Hello world”,将插入符放在“hello”和“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">');
}

关于javascript - 在 iframe 中的光标位置插入 HTML 控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7807129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com