Contenteditable - 从插入符号提取文本到元素末尾
浏览完所有可能的问题和答案后,我会尝试这种方式。
我正在编写 RTE 程序,但未能成功提取 contenteditable 元素中的文本。 原因是,每个浏览器处理节点和按键(#13)事件的方式略有不同(例如,一个浏览器创建“br”,另一个浏览器创建“div”、“p”等) 为了保持这一切一致,我正在编写一个跨浏览器编辑器,它使用 e.preventDefault(); 终止所有默认操作。
以下场景:
1) 用户按下 #13 键(检查)
2) 检测到插入符号位置(检查)
3) 在插入符号所在的元素后面创建新的 p(aragraph)(检查)
4) if text(node(s)) Between插入符和元素的末尾,提取它 (? ? ?)
5) 将文本(节点) 放入新创建的 p(aragraph) (检查)
正如你可以想象的,除了第 4 点之外,一切正常
。著名的 js rangey 库,其中正在提取特定的选择。
我需要的是以下内容:获取并提取从插入符号到可内容编辑段落(p,h1,h2,...)元素末尾的所有文本(当然带有标签,因此 splitBoundaries)。
欢迎任何线索、提示或片段! 提前致谢。
亲切的问候, p
after skimming all possible questions and answers, i'll try it this way.
I'm programming an RTE, but didn't manage to successfully extract text in a contenteditable element.
The reason for this is, that each browser handles nodes and keypress (#13) events in a slightly different way (as ex.g. one creates 'br', the other 'div', 'p', etc.)
To keep this all consistent, I'm writing a cross-browser editor which kills all default action with e.preventDefault();
Following scenario:
1) User hits the #13 key (check)
2) Caret position detected (check)
3) create new p(aragraph) after the element the caret's in (check)
4) if text(node(s)) between caret and the element's end, extract it (? ? ?)
5) put text(node(s)) to newly created p(aragraph) (check)
As you can imagine, everything works except point 4.
There's a similar functionality in the well-known js rangy library, where a specific selection is being extracted.
What i need is following: Get and extract all text (with tags of course, so splitBoundaries) from the caret on to the end of the contenteditable paragraph (p, h1, h2, ...) element.
Any clues, hints or snippets are welcome!
Thanks in advance.
Kind regards,
p
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过创建一个包含从插入符号到包含块元素末尾的内容的 Range 对象并调用其
extractContents()
方法来完成此操作:这在 IE <= 8 中不起作用,它不支持 Range 或与其他浏览器相同的选择对象。您可以使用 Rangy(您提到的)来提供 IE 支持。只需将
window.getSelection()
替换为rangy.getSelection()
即可。jsFiddle: http://jsfiddle.net/LwXvk/3/
You can do this by creating a Range object that encompasses the content from the caret to the end of the containing block element and calling its
extractContents()
method:This won't work in IE <= 8, which doesn't support Range or the same selection object as other browsers. You can use Rangy (which you mentioned) to provide IE support. Just replace
window.getSelection()
withrangy.getSelection()
.jsFiddle: http://jsfiddle.net/LwXvk/3/