简体   繁体   English

以编程方式在JavaScript中选择文本

[英]Programmatically selecting text in JavaScript

I know that you can call a certain form element to focus using JavaScript, which for some reason makes me feel like it shouldn't be hard to achieve my task. 我知道您可以使用JavaScript来调用某个表单元素来进行关注,出于某种原因,这使我觉得完成任务应该不难。 As part of a function, I want to leave the user with the contents of a particular div selected (so that they can easily copy it with control-c). 作为功​​能的一部分,我想让用户选择特定div的内容(以便他们可以使用control-c轻松复制它)。

In case it matters, the div contains content besides pure text (ie it contains the following two spans): 如果很重要,则div包含除纯文本之外的内容(即,它包含以下两个范围):

<span style="font-weight:bold; text-transform: capitalize;" id="part1"></span><span id="part2"></span>

No jquery, please. 请不要jquery。

How about : 怎么样 :

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> function selectText(){ document.getElementById('txt1').value = document.getElementById('xpto').innerHTML; document.getElementById('txt1').focus(); document.getElementById('txt1').select(); } </script> </head> <body> <div id="xpto"><span style="font-weight:bold; text-transform: capitalize;" id="part1"></span><span id="part2"></span></div> <form> <textarea id="txt1" name="txt1"></textarea> <button onclick="selectText()" type="button">Select text to copy</button> </form> </body> </html> 

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

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