【问题标题】:XHTML DOM - How to split a tag on IE?XHTML DOM - 如何在 IE 上拆分标签?
【发布时间】:2012-02-21 05:49:03
【问题描述】:

假设我有一个 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 或更多?

【问题讨论】:

    标签: dom xhtml tags split


    【解决方案1】:

    您可以使用选择范围获取选定的段。我建议使用rangy,它是一个跨浏览器范围模块。

    这里有一些使用 jQuery 和 Rangy 的“未经测试”的代码,希望为您的第一个案例指明正确的方向:

    var splitTag=function(class){
        var sel = rangy.getSelection();
    
        // this is your selection, in your example "is my first"
        var r0 = sel.getRangeAt(0);
    
        // create a new range       
        var r1 = rangy.createRange();
        // this would be your <p>
        var p = r0.endContainer.parentNode;
    
        // set the new range to start at the end of your phrase and to end at <p>
        r1.setStart(r0.endContainer, r0.endOffset);
        r1.setEnd(p, p.length-1);
    
        // extract the content of your first selection "is my first"
        var r0Txt=r0.toHtml();
    
        // make it into an span, with class set to "class argument" which would be 3 
        var newContent=$("<span/>").html(r0Txt).attr("class", class);
    
        r0.deleteContents();
    
        // insert the new node before r1
        r1.insertNode(newContent[0]);
        sel.removeAllRanges();
    }
    

    这应该会为您提供第一种情况的结果。对于跨多个段落的选择,这里是对代码的修改:

    var splitTag=function(class){
        var sel = rangy.getSelection();
    
        var r0 = sel.getRangeAt(0);
    
        var r1 = rangy.createRange();
        var p = r0.endContainer.parentNode;
    
        r1.setStart(r0.endContainer, r0.endOffset);
        r1.setEnd(p, p.length-1);
    
        var r0Txt=r0.toHtml();
    
        if(!r0.startContainer===r0.endContainer){
            // the selection spans multiple dom's
    
            // set the class of all spans in the highlight to 3
            var newContent=$(r0Txt).find("span").attr("class",class);
        }else{
            var newContent=$("<span/>").html(r0Txt).attr("class", class);
        }
    
        r0.deleteContents();
        r1.insertNode(newContent[0]);
        sel.removeAllRanges();
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-22
      • 2011-02-13
      • 2011-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多