Selecting text in a div programmatically using position values belong to that text

后端 未结 3 1767
暗喜
暗喜 2021-01-13 02:42

I have a div and there is a text in it.I want a part of that text to be selected programmatically according position value of characters.

3条回答
  •  自闭症患者
    2021-01-13 02:58

    Here is a simple way to to this:

    function selectTextRange(obj, start, stop) {
      var endNode, startNode = endNode = obj.firstChild
    
      startNode.nodeValue = startNode.nodeValue.trim();
      
      var range = document.createRange();
      range.setStart(startNode, start);
      range.setEnd(endNode, stop + 1);
      
      var sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
    }
    
    selectTextRange(document.getElementById('textdiv'), 3, 10);
    Hello world. I am a friend.


    Text highlight:

    function highlightRange(el, start, end) {
      var text = el.textContent.trim()
      el.innerHTML = text.substring(0, start) + 
        '' +
        text.substring(start, end) + 
        "" + text.substring(end);
    }
    
    highlightRange(document.getElementById("textdiv"), 3, 10)
    Hello world. I am a friend.

提交回复
热议问题