jQuery surround highlighted text with SPAN

限于喜欢 提交于 2019-12-28 06:35:28

问题


The following code is supposed to surround the highlighted text in a given Div with a span.

$(document).ready(function(){
    $('.format').click(function(){
       var highlight = window.getSelection();

        var spn = '<span class="highlight">' + highlight + '</span>';
        $('.conttext').content().replace(highlight, spn);

    });
});

A function of this nature could be used to provide formating options to an HTML contenteditable DIV.

Something is clearly wrong though as it does not currently work.

http://jsfiddle.net/BGKSN/20/


回答1:


DEMO: http://jsfiddle.net/BGKSN/24/

$(document).ready(function(){
    $('.format').click(function(){
        var highlight = window.getSelection();  
        var spn = '<span class="highlight">' + highlight + '</span>';
        var text = $('.conttext').text();
        $('.conttext').html(text.replace(highlight, spn));
    });
});

Later Edit:

Based on the comment, this is the real functional example:

http://jsfiddle.net/BGKSN/40/

$(document).ready(function(){
    $('.format').click(function(){
        var highlight = window.getSelection(),  
        spn = '<span class="highlight">' + highlight + '</span>',
        text = $('.conttext').text(),
        range = highlight.getRangeAt(0),
        startText = text.substring(0, range.startOffset), 
        endText = text.substring(range.endOffset, text.length);

        $('.conttext').html(startText + spn + endText);
    });
});

Docs: https://developer.mozilla.org/en-US/docs/Web/API/window.getSelection




回答2:


Well, first off, you had your html wrong, something like this
<a href="" class="format">test</div>

Secondly, when you tried to click test it deselected the selected text because this is what happens if you click somewhere when you have some text selected. So, with this in mind, I changed it to $("body").keypress() so it will wrap the highlighted text in span when a key is pressed. Also, fixed some of the jQuery code and voila, it works!

Check it out here.

If you fix your anchor tag and your jQuery a bit $(".contenttext").contents() where .contents() is a non-existand function to
$(".contenttext").html($(".contenttext").html().replace(highlight, spn));
it works as expected as seen here.



来源:https://stackoverflow.com/questions/17836488/jquery-surround-highlighted-text-with-span

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!