如何兼容、灵活的插入字符串

ie系列(6+),支持object.insertAdjacentHTML(where, html),查看使用方法和参数:MSDN:http://msdn.microsoft.com/en-us/library/ms536452%28VS.85%29.aspx

firefox与chrome已支持此系列方法(包含:object.insertAdjacentTextobject.insertAdjacentElement ,firefox仅支持了HTML的api)

如果浏览器是早期版本,可以使用 range.createContextualFragment,将字符串转为dom tree。此方法返回一个DocumentFragment

然后使用insertBefore、appendChild、innerHTML方法来实现

做富文本编辑,会经常使用此api range.createContextualFragment、range.setStartBefore 来实现添加文本,设置位置。

代码实现参考http://www.w3help.org/zh-cn/causes/SD9016

原文地址:https://www.cnblogs.com/henryli/p/3465132.html