在一个contenteditable div中的html中包含光标 [英] Wrap cursor in html in a contenteditable div

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

问题描述

我希望将游标包含在 span 标记中,并且在可信任的 div 中。

I'm looking to wrap a cursor in span tags in a contenteditable div.

示例(由 | 表示的游标):

Example (cursor represented by |):


  • 之前:

狐狸跳跃|


  • 之后:

狐狸jumps< span> |< / span>

任何修改innerHTML的尝试都会导致光标移动到结尾线。我希望它插入之间新的HTML span

Any attempt to modify the innerHTML results in the cursor being moved to the end of the line. I'd like it to be inserted in between the new HTML span's.

推荐答案

由于实施问题,这不可能跨浏览器。尝试将插入符号放在WebKit和IE中的空内联元素(例如< span> )中,实际上会将插入符号放在元素之前。以下内容证明了这一点:它可以满足您对Firefox的期望,但不会是WebKit或IE。

This isn't possible cross-browser because of implementation issues. Attempting to place the caret within an empty inline element such as a <span> in both WebKit and IE will actually place the caret immediately before the element. The following demonstrates this: it will do you what you expect in Firefox but not WebKit or IE.

http://jsfiddle.net/8TTb3/1/

您可以使用 DOM范围选择用于在插入符号位置插入元素的API,除了IE< 9不支持这些,而是​​有自己的API。

You can use a DOM Range and the Selection API to insert elements at the caret position, except in IE < 9 which does not support these and instead has its own API.

代码:

var range = sel.getRangeAt(0);
var span = document.createElement("span");
range.insertNode(span);
range.setStart(span, 0);
range.setEnd(span, 0);
sel.removeAllRanges();
sel.addRange(range);

这篇关于在一个contenteditable div中的html中包含光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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