XHTML DOM - 如何在 IE 上拆分标签?
假设我有一个 html 文档的一部分,其中包含以下代码(基本结构):
<p>
<span class="1">This is my first content</span>
<span class="2">This is my second content</span>
</p>
我想允许用户选择文本的一部分并向其应用一个新类。 假设用户在第一个跨度中选择“是我的第一个”,并应用类“3”。 我希望得到以下结果:
<p>
<span class="1">This </span>
<span class="3">is my first</span>
<span class="1"> content</span>
<span class="2">This is my second content</span>
</p>
我已经设法通过使用 execCommand“InsertHTML”在 Firefox 上执行此操作,但我找不到在 IE 中执行此操作的方法(IE9 之前) 我唯一的结果是一个嵌套的 span 元素,如下所示:
<p>
<span class="1">This <span class="3">is my first</span> content</span>
<span class="2">This is my second content</span>
</p>
您知道我如何实现这一目标吗? 任何帮助将不胜感激! 顺便说一句,如果这对您来说太简单了,那么您将如何处理用户选择跨越 2 个或更多跨度的文本部分的情况?超过 2 个或更多 ps ?
Let's assume I have a part of an html document containing the following code (basic structure) :
<p>
<span class="1">This is my first content</span>
<span class="2">This is my second content</span>
</p>
I'd like to allow the user to select a part of the text and apply a new class to it.
Let's say the user selects "is my first" in the first span, and applies class "3".
I'd like to have the following result :
<p>
<span class="1">This </span>
<span class="3">is my first</span>
<span class="1"> content</span>
<span class="2">This is my second content</span>
</p>
I've managed to do this on Firefox by using the execCommand "InsertHTML", but I can't find a way to do this in IE (before IE9)
The only result I have is a nested span element, like below :
<p>
<span class="1">This <span class="3">is my first</span> content</span>
<span class="2">This is my second content</span>
</p>
Do you have any idea of how I could achieve this ?
Any help would be much appreciated !
By the way, if this looks too simple to you, how would you handle the case of a user selecting a portion of text that spans over 2 or more spans ? over 2 or more ps ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用选择范围获取选定的段。我建议使用 rangy,它是一个跨浏览器范围模块。
这里有一些使用 jQuery 和 Rangy 的“未经测试”的代码,希望能为您的第一种情况指明正确的方向:
这应该可以为您提供第一种情况的结果。对于跨多个段落的选择,以下是代码的修改:
you can get the selected segment using selection range. I would recommend using rangy, which is a cross browser range module.
Here's some "untested" code using jQuery and Rangy to hopefully point you in the right direction, for your first case:
this should get you the result for your first situation. for selections across multiple paragraphs, here's a modification of the code: