简体   繁体   中英

Selecting text in a div programmatically and simultaneously by selecting same text in textarea

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.

<div id="textdiv">
Hello world. I am a friend.
</div>

I want "llo world" part to be selected(I mean highlighted/selected like making selection of content in an input/textarea ). In that case position values are first (3) and last (10).

But when i try select a part of text in textarea and get the same text selected in other div, it doesn' t select the same text, it selects from the beginning of text to the first position value which is "He" part in this case.

<body>
<div style="display:block;display:inline-block;float:left;border:1px solid green;">
<textarea id="textarea_" style="height:4em;width:200px;">Hello World! I am friend!</textarea>
</div>
<div id="otherdiv" style="border:1px solid black;display:inline-block;height:4em;width:200px;float:left;clear:left;">
Hello World! I am friend!
</div>
<script>
$(function(){   

var otherdiv=document.getElementById('otherdiv');
var selectionafter ;
var selectionstart ;
var diff;
var range;
var endNode, startNode;
var textare=$('#textarea_');
var sel = document.getSelection();

textare.on('mousedown', function(event){
  textare.on('mousemove', function(event){
     selectionafter=event.target.selectionEnd;
     selectionstart=event.target.selectionStart;

     diff=selectionafter-selectionstart;
     if(selectionafter!=0 && selectionstart!=0 && diff!=0){
      endNode, startNode = endNode = otherdiv.firstChild; 
      startNode.nodeValue = startNode.nodeValue.trim();

      range = document.createRange();
      range.setStart(startNode, selectionstart);

      range.setEnd(endNode, selectionafter+1);

      sel.removeAllRanges();
      sel.addRange(range);  
    }
  });
}); 
});
</script>
</body>

jsFiddle

You should not do all that stuff inside a mousemove event handler.

Here is a corrected version that works using a select event handler: jsFiddle

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