简体   繁体   中英

Position changes every time with window.getSelection()

Can anyone help me? I got these codes here https://stackoverflow.com/a/17836828/2338164

$(document).on("mouseup",".wrap",function(){
    var highlight = window.getSelection();
    if(highlight.toString().length>=1){
        var spn = '<span class="highlight">' + highlight + '</span>';
        var text = $(this).text();
        var range = highlight.getRangeAt(0);
        var startText = text.substring(0, range.startOffset);
        var endText = text.substring(range.endOffset, text.length);
        $('#q3txt').append(range.startOffset+"<br>");
        $(this).html(startText + spn + endText);
    }
});

I tried to use it and it's working fine, until you highlight again...

Here's a link http://jsfiddle.net/AN76g/ .

What im trying to do is... user will highlight a block then wrap it in span, but if the user made a mistake and tries to highlight again, the span is removed and will try to wrap the new highlighted text. But either the position changes or parts of the text are being appended.

See this update: jsfiddle .

First, on the mousedown, you can unwrap the span as so:

$(document).on("mousedown",".wrap",function(){      
    $('.highlight').contents().unwrap();
});

Secondly, the problem with using the range.startOffset and range.endOffset is that you the start is relative to the containing element which could be the highlight span which causes you to replace the incorrect text on subsequent selections. Instead, replace the selection with the span as so:

$(document).on("mouseup",".wrap",function(){
    var highlight = window.getSelection();      
    if(highlight.toString().length>=1){         
        var range = highlight.getRangeAt(0);
        var selectionContents = range.extractContents();
        var spn = document.createElement("span");
        spn.className='highlight';
        spn.appendChild(selectionContents);         
        range.insertNode(spn);
        highlight.removeAllRanges();
    }
}); 

Information from MDN Range.startOffset , specifically:

the startContainer is a Node of type Text, Comment, or CDATASection, then the offset is the number of characters from the start of the startContainer to the boundary point of the Range. For other Node types, the startOffset is the number of child nodes between the start of the startContainer and the boundary point of the Range.

Also, this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM