使用选择和范围对象的 JavaScript 标记编辑器
我正在尝试使用选择和范围对象编写一个基于 JavaScript 的标记编辑器(WYSIWIG)。到目前为止,我访问这些对象没有任何问题。
我的问题从这里开始:
使用 range 对象,我可以访问其属性 startContainer/StartOffset 和 EndContainer/Endoffset。这意味着我得到有关我的选择开始的节点的信息,包括内部位置和有关选择结束的相同信息。
据我所知,JavaScript 会自动添加开始或结束标签,以防我的选择破坏现有的树结构。
如果我现在想添加一些标记,我该如何处理这些损坏的结构?
示例:
This <i>is my</i><b>sample</b> text.
现在我想强调“我的样本”部分,
这意味着必须根据“我的样本”的选择构建类似的东西:
This <i>is <u>my</u></i><b><u>sample</u></b> text.
但是由于我没有注意到现有树结构的破坏,我怎样才能做这个吗?如何确保标记有效?
我也在考虑处理整个字符串,但我不知道字母/文本的全局位置,只知道它们在某些节点内的位置。
我希望这个问题是清楚的,并且我对其一般形式表示歉意。但我真的对这些东西感到疯狂......
I am trying to write a JavaScript based Markup Editor (WYSIWIG) using the selection and the range object. I have no problems so far to access these objects.
My problems begin here:
Using the range object, I can access its properties startContainer/StartOffset and EndContainer/Endoffset. That means I get back the information about the node my selection starts in including the internal position and the same information about the end of the selection.
As far as I have understood, JavaScript automatically adds starting or ending tags in case my selection breaks existing tree structures.
If I want to add some markup now, how can I deal with these broken structures?
Example:
This <i>is my</i><b>sample</b> text.
Now I would like to underline the part "my sample"
That means something like this has to be constructed out of the selection of "my sample":
This <i>is <u>my</u></i><b><u>sample</u></b> text.
But since I do not notice the breaking of a prexisting tree structure, how can I do this? How can I ensure valid markup?
I was also thinking about processing the whole string, but I do not know about the global positions of letters/text but only about their position within certain nodes.
I hope this question is clear and I apologize for its general form. But I am really getting crazy about this stuff ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有内置方法
document.execCommand()
(MSDN, MDN),它会为您处理这些内容。如果是下划线,则为jsFiddle: http://jsfiddle.net/3NcEP/
请注意,仅适用于大多数浏览器中的可编辑内容(使用
contenteditable
或designMode
)。如果您需要对内置命令之一未提供的选择应用某种样式,则需要自己处理选择中的所有节点,并根据需要在选择的每一端进行分割。这一点很重要。另外,IE < 9 不支持 DOM Range 和
选择
并以完全不同的方式做事。如果您需要处理这些浏览器,像我自己的 Rangy 这样的库可以提供帮助。There is the built-in method
document.execCommand()
(MSDN, MDN), which handles this stuff for you. In the case of underline, it would bejsFiddle: http://jsfiddle.net/3NcEP/
Note that this only works on editable content (using
contenteditable
ordesignMode
) in most browsers.If you need to apply some styling to the selection that isn't provided by one of the built-in commands, you'll need to handle all the nodes within the selection yourself, splitting if necessary at each end of the selection. This is non-trivial. Also, IE < 9 does not support DOM Range and
Selection
and does things completely differently. If you need to handle these browsers, a library like such as my own Rangy can help.