You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何实现选中<p>标签内文本并完成复制功能

实现点击按钮选中并复制<p>标签内文本

针对普通标签的文本选中复制需求,可直接使用如下完整可运行代码:

<!DOCTYPE html>
<html>
<body>

<p>Click on the button to copy the text from the paragraph. Try to paste the text (e.g. ctrl+v) afterwards in a different window, to see the effect.</p>

<!-- 给需要选中复制的p标签设置id用于定位 -->
<p id="myPara">这是p标签内需要被选中复制的测试文本</p>
<button onclick="copyParaText()">Copy text</button>

<script>
function copyParaText() {
  // 获取目标p标签元素
  const para = document.getElementById("myPara");

  // 创建选区,实现文本高亮选中效果
  const range = document.createRange();
  const selection = window.getSelection();
  // 将选区范围设置为p标签内的全部内容
  range.selectNodeContents(para);
  // 清空页面上已有的选中状态
  selection.removeAllRanges();
  // 应用新选区,此时页面上就会显示文本高亮选中的效果
  selection.addRange(range);

  // 将文本写入系统剪贴板
  navigator.clipboard.writeText(para.innerText);
  
  // 复制成功提示
  alert("Copied the text: " + para.innerText);
}
</script>

</body>
</html>

实现说明

  • 原w3schools示例中使用的.select()、.setSelectionRange()是<input>、<textarea>这类表单输入元素的专属方法,无法直接作用于<p>、<div>这类普通DOM节点。
  • 普通节点的文本选中需要借助浏览器原生Range和Selection API实现,选中后视觉效果和输入框文本选中完全一致。
  • p标签选中文本的预期效果如下:
    p标签选中文本预期效果
  • 原输入框选中文本的效果参考:
    input选中文本效果
  • 代码兼容所有现代浏览器,移动端也可正常触发选中和复制逻辑,选中文本后直接按Ctrl+V(macOS为Cmd+V)即可粘贴内容。

内容的提问来源于stack exchange,提问作者Dile

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 11:45:52