contentEditable div动态替换innerHTML [英] contentEditable div replace innerHTML on the fly

查看:417
本文介绍了contentEditable div动态替换innerHTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法(Rangy库除外)动态更改contentEditable Div InnerHTML,就像在keyup上一样,没有光标位置/焦点丢失?我想使用纯JavaScript代码,尽可能简单。

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.

例如:

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

然后javascript:

then javascript :

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

谢谢。

推荐答案

如果您要替换HTML,则需要一些保存和恢复选择的方法。选项包括:

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


  1. 在HTML替换之前在选择的开头和结尾插入带有ID的元素,然后通过ID检索它们并移动使用这些元素的选择边界。这是最强大的方法,也是Rangy所做的。

  2. 在HTML替换之前为选择的开始和结束存储某种基于字符的偏移量,然后重新创建选择。这在一般情况下会出现各种问题,但可能会很好,具体取决于您的需求。我已经在SO之前公布的功能依赖于Rangy,如果你不介意失去对IE的支持,你可以轻松地删除Rangy的东西。 9。

  3. 按像素坐标存储和恢复选择边界。浏览器对此的支持并不好,如果您的HTML替换更改了布局,则不适合。

  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.

这篇关于contentEditable div动态替换innerHTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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