contentEditable div replace innerHTML on the fly

ぃ、小莉子 提交于 2019-12-31 03:21:26

问题


Is there a way ( except Rangy library ) to change contentEditable Div InnerHTML on the fly, like on keyup, with no cursor position / focus lose? I'd like to use pure javascript code, as simple as it is possible.

for example :

<div id="divId" contentEditable="true" onkeyup="change(this)"></div>

then javascript :

function change(element)
{
  element.innerHTML = element.innerHTML.replace(/.../, '...');
}

Thanks.


回答1:


If you're replacing the HTML, you will need some means of saving and restoring your selection. The options are:

  1. Insert elements with IDs at the start and end of the selection before the HTML replacement, retrieve them by ID afterwards and move the selection boundaries using those elements. This is the most robust method and is what Rangy does.
  2. Store some kind of character-based offset for the start and end of the selection before the HTML replacement and recreate the selection afterwards. This has all kinds of problems in the general case but may be good enough, depending on your needs. I've posted functions on SO to do this before that depend on Rangy, but you could easily strip out the Rangy stuff if you don't mind losing support for IE < 9.
  3. Store and restore selection boundaries by pixel coordinates. Browser support for this is not good and will not be suitable if your HTML replacement changes the layout.



回答2:


This doesn't use the keyup event but perhaps it will suffice? Note that applies to the body you can obviously target just a certain element.

document.body.contentEditable='true';
document.designMode='on';
void 0;


来源:https://stackoverflow.com/questions/7402794/contenteditable-div-replace-innerhtml-on-the-fly

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