Wrap cursor in html in a contenteditable div

假装没事ソ 提交于 2019-12-06 04:33:23

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/

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.

Code:

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);

Actually, you can do a trick:

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

works in chrome: http://jsfiddle.net/8TTb3/8/

The only thing you can control is the position of the cursor in the (already parsed) contents of the div. If you put a span in there it will be parsed before the cursor is inserted by the browser, at which point the cursor will be either before it or after it.

So no, I don't think this is possible.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!