jQuery surround highlighted text with SPAN

2019-01-15 09:27发布

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/

2条回答
乱世女痞
2楼-- · 2019-01-15 10:09

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

查看更多
爷的心禁止访问
3楼-- · 2019-01-15 10:31

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.

查看更多
登录 后发表回答