Get the highlighted text position in .html() and .text()

前端 未结 1 1011
不思量自难忘°
不思量自难忘° 2021-01-02 12:28

I am using the following script to get the position of highlighted text:

function getSelectionCharOffsetsWithin(element) {
    var start = 0, end = 0;
    va         


        
相关标签:
1条回答
  • 2021-01-02 13:14

    From your comment, this is what you want to accomplish.

    i will try to explain this as good as i can. English is not my native language, so sorry for the confusion. I would like to insert a html-tag before and after the highlighted text. To achieve this, i will have to get the beginning and end of the text.

    Assuming sit is the highlighted selection you want to process.

    You can use .wrap() or .after() and .before() to accomplish this.

    function alertSelection() {
        $("b", $('#detailBoxParagraph')).wrap('<i/>'); // make the  highlighted section inside a tag.
    
        $("b", $('#detailBoxParagraph')).before('<u>Content inserted before </u> '); // insert an html before highlighted selections.
    
        $("b", $('#detailBoxParagraph')).after(' <u>Content inserted after </u>'); // insert an html after highlighted selections.
    }
    
    $(function () {
        alertSelection();
    })
    

    Here I'm making the highlighted text italics.

    See sample in jsFiddle

    Reference

    • .wrap()
    • .before()
    • .after()

    If you are trying to accomplish the selected text to highlight, you can use jQuery highlight plugin.

    See sample in jsFiddle.

    function getSelectionText() {
        var text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        } else if (document.selection && document.selection.type != "Control") {
            text = document.selection.createRange().text;
        }
        return text;
    }
    
    $(function () {
        $('#detailBoxParagraph').mouseup(function (e){
            $(this).removeHighlight();
            $(this).highlight(getSelectionText());
       });
    });
    
    0 讨论(0)
提交回复
热议问题