我试图将<span>
元素注入用户在contenteditable
<div>
中输入的文字中。输入事件(DOMCharacterDataModified
)定期触发对标识文本中某些实体的服务的请求,并且我希望相应地更新它。例如,
<div id="editor" contenteditable="true">
The New York Times is an American newspaper based
in New York City with worldwide influence and
readership.
</div>
变为
<div id="editor" contenteditable="true">
The <span class="name">New York Times</span> is an
American newspaper based in <span class="loc">New
York City</span> with worldwide influence and
readership.
</div>
我是否可以在不替换<span>
内容的情况下注入<div>
个元素,从而保留用户的文本光标位置?
答案 0 :(得分:0)
我不知道它是否会保留文本光标位置,但是直截了当的JavaScript replace()应该有效,无论它是否在contenteditable
内。
str.replace("New York Times", "<span>New York Times</span>")