实现点击按钮复制文本框内容到剪贴板(原生JS)

前言

在这里插入图片描述
这里需要使用 document.execCommand() API,执行一个对当前文档,当前选择或者给出范围的命令,来处理 HTML 数据,用于实现复制功能。

document.execCommand()

【语法】

bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

【返回值】

布尔值 ,如果是 false 则表示操作不被支持或未被启用。

注意:在调用一个命令前,不要尝试使用返回值去校验浏览器的兼容性。

【参数】

  1. aCommandName:一个 DOMString ,命令的名称。可用命令列表请参阅命令 (我们用 “copy” 命令)。
  2. aShowDefaultUI:一个 Boolean, 是否展示用户界面,一般为 false(Mozilla 没有实现)。
  3. aValueArgument:一些命令(例如 insertImage)需要额外的参数(insertImage 需要提供插入 image 的 url),默认为 null。

实现

通过了解 document.execCommand() API,或许你已经有了思路。

【HTML】

<input type="text" id="input" value="hello">
<button id="button" onclick="copy()">点击复制</button>

【JavaScript】

// 实现复制到剪贴板功能函数
function copy(){

  // 获取输入框元素
  let input = document.getElementById('input')

  // 选中元素中的文本(必须可编辑)
  input.select()

  // 检测复制命令返回值(是否可用)
  if(document.execCommand('copy')){
    document.execCommand('copy')//执行复制到剪贴板
    window.alert('已复制!')//反馈信息
  }
  
  // 无法复制(不可用)
  else{
    window.alert('复制失败!')//反馈信息
  }
}

在这里插入图片描述

写在后面

以上是一个非常简单的 demo,如果你想进一步探索,请移步 MDN

扫描二维码关注公众号,回复: 11277653 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_44198965/article/details/106360884