【问题标题】:jQuery - Wrap <span> around selected text - duplicate instance bugjQuery - 围绕选定文本包裹 <span> - 重复实例错误
【发布时间】:2012-05-23 11:09:18
【问题描述】:

这个问题引用了一个类似的问题asked here,关于如何将标签应用于选定的文本。问题已得到解答,但该答案有一个主要缺陷,即如果所选文本存在于文档的其他位置,&lt;span&gt; 将环绕副本,而不是相关文本。

我意识到这可能违反了某些 stackoverflow 协议,但我在这里发帖时并没有真正了解如何继续。我最好的猜测是以某种方式找到所选文本之前的字符串长度(along these lines),但如何将其合并到替换函数本身......好吧我可以使用推送。任何人?

(我已将解决方案粘贴到之前的帖子(mathias-bynens)下面。)

    $("p").live("mouseup",function() {
    selection = getSelectedText();
    if(selection.length >= 3) {
        var spn = '<span class="selected">' + selection + '</span>';
        $(this).text($(this).html().replace(selection, spn));

    }
});

//Grab selected text
function getSelectedText(){
    if(window.getSelection){
        return window.getSelection().toString();
    }
    else if(document.getSelection){
        return document.getSelection();
    }
    else if(document.selection){
        return document.selection.createRange().text;
    }
}

【问题讨论】:

    标签: jquery cursor-position string-length replace


    【解决方案1】:

    我认为您的关键是弄清楚 getSelection 返回的内容并使用它。

    在 Firefox 上我能够做到这一点:

    $(document.getSelection().anchorNode).wrap('<div style="color:blue">')
    

    document.selection.createRange() 必须有一个类似的东西可以让你找到被选中的东西。

    类似:

    $("p").live("mouseup",function() {
        var $sel = getSelectedElem();
        if($.trim($sel.text()).length >= 3) {
            $sel.warp('<span class="selected">');
        }
    });
    
    //Grab selected text
    function getSelectedElem(){
        if(window.getSelection){
            return $(window.getSelection().anchorNode);
        }
        else if(document.getSelection){
            return $(document.getSelection().anchorNode)
        }
        else if(document.selection){
            //todo figure out what to return here:
            return document.selection.createRange().text;
        }
        return $([]);
    }
    

    【讨论】:

      【解决方案2】:

      我作弊了,用document.execCommand把选中的文本包裹起来,然后用href(CreateLink execCommand的第三个参数)找到元素,用我想要的包裹起来,然后去掉链接:

      $("p").live("mouseup",function() {
          document.execCommand('CreateLink', false, 'uniqueid');
          var sel = $('a[href="uniqueid"]');
          sel.wrap('<span class="selected" />')
          sel.contents().unwrap();
      });
      

      所有主要浏览器都支持document.execCommand,因此您应该安全地以这种方式破解它。在我测试过的浏览器中,浏览器本身会为你关闭和打开标签,所以如果你从一个html标签的中间选择到另一个html标签的中间,它应该正确嵌套标签。

      【讨论】:

      • 我喜欢这个。在这被冲洗掉之前,这似乎是处理这个问题的好方法。
      【解决方案3】:

      这个呢?

      document.execCommand("insertHTML", false, "<span class='own-class'>"+ document.getSelection()+"</span>");
      

      sourceYeppThat'sMe

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-24
        • 1970-01-01
        • 1970-01-01
        • 2016-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多