在Javascript contenteditable div中插入文字 [英] Insert text in Javascript contenteditable div

查看:453
本文介绍了在Javascript contenteditable div中插入文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我需要插入一个文本(字符串,可能有或没有html标签)到div。它必须是一个div而不是一个textarea。

I have a problem where I need to insert a text (string, may or may not have html tags) to a div. It has to be a div and not a textarea.

有没有反正呢?首先,我需要获取光标位置,然后在该位置插入文本。

Is there anyway to do that? First of all, I need to get the cursor position, then inserting the text in that position.

它类似于function insertAdjacentText,但它只能插入前标签,并且只能在IE中使用。

It's similar to function insertAdjacentText, but it can only insert before or after a tag, and only works in IE.

请参阅此网址: http://yart.com.au/test/iframe.aspx 。注意如何将光标放在div中,我们需要在光标位置添加文本。

Refer to this URL: http://yart.com.au/test/iframe.aspx. Note how you can position the cursor in the div, we need to add text at the cursor location.

推荐答案

要做的是在当前选择/插入点插入HTML,这是可行的。

If all you need to do is insert HTML at the current selection / insertion point, that is doable. Off the top of my head (to get you started):

在IE中,使用document.selection.createRange()。pasteHTML(theNewHTML)。

In IE, use document.selection.createRange().pasteHTML(theNewHTML).

在其他浏览器中,您应该能够使用document.execCommand(InsertHTML,...)。

In other browsers, you should be able to use document.execCommand("InsertHTML", ...).

只有在可编辑的iframe /文档中使用这些技术,而不是div,但是如果div是集中的话,这些调用应该可以工作。

I've used these kinds of techniques only in editable iframes/documents, not divs, but these calls should work if the div is focused, I believe.

另一个答案警告说,它会变得丑陋,如果你想更细粒度的控制,如在其他地方插入文本。

As another answer warned, it gets ugly if you want finer-grained control, like inserting text in other places.

这篇关于在Javascript contenteditable div中插入文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆