jQuery - 围绕选定的文本包裹<span> - 重复的实例错误</span>

时间:2012-05-15 21:39:57

标签: jquery cursor-position string-length replace

此问题引用了一个类似的问题asked here,关于如何将标记应用于所选文本。问题得到了回答,但是这个答案有一个主要缺陷,即如果文档中其他位置存在所选的相同文本,则<span>会包围副本,而不是相关文本。

我意识到这可能是针对某些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;
    }
}

3 个答案:

答案 0 :(得分:4)

我作弊,并使用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标签的中间选择到另一个的中间,它应该正确地嵌套标签。

答案 1 :(得分:0)

我认为你的关键是找出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 :(得分:0)

这个怎么样?

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

YeppThat'sMe

相关问题