在可编辑 iframe 中使用 execCommand() 时如何执行与退格键相同的操作?

发布于 2024-12-28 10:36:19 字数 197 浏览 3 评论 0原文

我使用 execCommand 和 javascript 将文本插入到可编辑的 iframe 中,如下所示:

element.execCommand("insertHTML",false,"some text");

有人知道如何插入该文本而不是光标左侧的第一个字符吗?那么与执行上述操作之前按退格键的效果相同吗?

I am using execCommand with javascript to insert text into editable iframes like this:

element.execCommand("insertHTML",false,"some text");

Anyone know how to insert that text instead of the first character to the left of the cursor? So the same effect as pressing a backspace before doing the above?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉栀 2025-01-04 10:36:19

似乎没有简单的方法将击键发送到可编辑的 iframe,因此您可能需要找到某种解决方法。最简单的方法是从 iframe 获取内容,操作它们,然后将它们放回 iframe。

例如:
选择 iframe 中的所有文本以

var selection = element.execCommand("selectAll");

删除最后一个字符 - 切片选择

selection = selection.baseNode.data.slice(0, -1)

删除所有内容

element.execCommand("Delete")

附加切片选择+您的新文本

element.execCommand("insertHTML",false,selection);
element.execCommand("insertHTML",false,"some text");

参考:

  1. http://msdn.microsoft.com/en-us/library/ie/ms533049(v=vs.85).aspx
  2. https://developer.mozilla.org/en/Rich-Text_Editing_in_Mozilla

PS我注意到非常熟悉可编辑的 iframe 或选择对象,因此如果您的文本中有任何特殊字符的 html,它可能比这复杂得多。此外,您可能需要针对不同的浏览器进行调整。

It seems that there's no easy way to send keystrokes to editable iframe, so you'll probably need to find some sort of workaround. Easiest way to do that would be to get the contents from iframe, manipulate them and then put them back to iframe.

E.g.:
Select all text in iframe with

var selection = element.execCommand("selectAll");

to remove last character - slice selection

selection = selection.baseNode.data.slice(0, -1)

delete all content

element.execCommand("Delete")

append sliced selection + your new text

element.execCommand("insertHTML",false,selection);
element.execCommand("insertHTML",false,"some text");

References:

  1. http://msdn.microsoft.com/en-us/library/ie/ms533049(v=vs.85).aspx
  2. https://developer.mozilla.org/en/Rich-Text_Editing_in_Mozilla

P.S. I'm note very familiar with editable iframe or selection objects, so if you have any html of special characters in your text it might be much more complicated than this. Also you might need to tweak it for different browsers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文