How do I extend selection to word boundary using JavaScript, once only?

后端 未结 3 1589
感动是毒
感动是毒 2020-12-15 12:02

I\'m using the technique shown in this answer to extend a web page\'s selection to a word boundary:

function snapSelectionToWord() {
    var sel;

    // Che         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 12:30

    your code does not work properly in arabic text you can try this snippet nstead

    function snapSelectionToWord() {
        var sel;
    
        // Check for existence of window.getSelection() and that it has a
        // modify() method. IE 9 has both selection APIs but no modify() method.
        if (window.getSelection && (sel = window.getSelection()).modify) {
            sel = window.getSelection();
            if (sel.isCollapsed) {
               
               var rng2 = sel.getRangeAt(0);
               var startOffset = rng2.startOffset;
               startOffset = 0
               for (var i = rng2.startOffset; i >= 0; i--) {
                  if (rng2.startContainer.data[i].match(/\S/) != null) {
                     startOffset++;
                  } else
                     break;
               }
               var endOffset = rng2.endOffset;
               endOffset = 0;
               for (var i = rng2.endOffset; i < rng2.endContainer.data.length; i++)
                  if (rng2.endContainer.data[i].match(/\S/)) {
                     endOffset++;
                  } else
                     break;
    
               startOffset = rng2.startOffset - startOffset;
               startOffset = startOffset < 0 ? 0 : startOffset;
    
               endOffset = rng2.endOffset + endOffset;
               endOffset = endOffset >= rng2.endContainer.data.length ? rng2.endContainer.data.length - 1 : endOffset;
    
               rng2.setStart(rng2.startContainer, startOffset);
               rng2.setEnd(rng2.endContainer, endOffset);
               sel.removeAllRanges();
               sel.addRange(rng2);
               
            }
        } else if ( (sel = document.selection) && sel.type != "Control") {
            var textRange = sel.createRange();
            if (textRange.text) {
                textRange.expand("word");
                // Move the end back to not include the word's trailing space(s),
                // if necessary
                while (/\s$/.test(textRange.text)) {
                    textRange.moveEnd("character", -1);
                }
                textRange.select();
            }
        }
    }

提交回复
热议问题