Wrap cursor in html in a contenteditable div

一笑奈何 提交于 2019-12-08 01:50:49

问题


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

Example (cursor represented by |):

  • Before:

The fox jumps |

  • After:

The fox jumps <span>|</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.


回答1:


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



回答2:


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/




回答3:


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.



来源:https://stackoverflow.com/questions/13555681/wrap-cursor-in-html-in-a-contenteditable-div

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