简体   繁体   English

选择文本并同时在 textarea 和 div 中使用 javascript 突出显示

[英]selected text and Highlight with javascript in textarea and div at the same time

selected text and Highlight with javascript in textarea and div at the same time选择文本并同时在 textarea 和 div 中使用 javascript 突出显示

this demo just shows the selected text in div, but I need to show the same text in both books, just show what text is Highlighted in div or textarea at the same time这个演示只是在 div 中显示选定的文本,但我需要在两本书中显示相同的文本,只需同时显示在 div 或 textarea 中突出显示的文本

 <!DOCTYPE html> <html> <body> <p id="test">This example uses the addEventListener() method to attach a "select" event to an element.</p> <input style="width:100%" type="text" value="Only text in the input field is being displayed when selected!" id="myText"> <p id="demo"></p> <script> document.addEventListener("mouseup", function(){ if(document.getSelection()){ document.querySelector("#demo").textContent = document.getSelection(); }else if(window.getSelection()){ document.querySelector("#demo").textContent = document.getSelection(); }else if(document.selection){ document.querySelector("#demo").textContent = document.selection.createRange().text; } }); </script> </body> </html>

chek my screenshot检查我的屏幕截图

在此处输入图片说明

I just need to show the text what is selected in textarea or div need to change color in both blocks at the same time我只需要显示在 textarea 或 div 中选择的文本需要同时更改两个块中的颜色

also, my textarea don't have id or class - and I want to keep it this way另外,我的 textarea 没有 id 或 class - 我想保持这种方式

<textarea></textarea>

thank you - if you can show a javascript example will be very helpful.谢谢 - 如果你能展示一个 javascript 示例将会非常有帮助。

you can select textarea with:您可以使用以下命令选择 textarea:

document.querySelector("textarea").style.backgroundColor = "yellow";

window.getSelection() has all the properties to count offset of the selection from the entire text. window.getSelection() 具有计算整个文本中选择的偏移量的所有属性。

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

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