简体   繁体   English

通过在textarea中选择相同的文本以编程方式同时选择div中的文本

[英]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,其中有一个文本,我希望根据字符的位置值以编程方式选择该文本的一部分。

<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 ). 我希望选择“ llo world”部分(我的意思是突出显示/选择内容,就像在input / textarea中选择内容一样)。 In that case position values are first (3) and last (10). 在这种情况下,位置值是前(3)和后(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. 但是,当我尝试在textarea中选择文本的一部分并在其他div中选择相同的文本时,它没有选择相同的文本,而是从文本的开头到第一个位置值(即“ He”部分)进行选择案件。

<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 jsFiddle

You should not do all that stuff inside a mousemove event handler. 您不应该在mousemove事件处理程序中做所有这些事情。

Here is a corrected version that works using a select event handler: jsFiddle 这是使用select事件处理程序的更正版本: jsFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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