获得焦点并且复制文本


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>

</style>
</head>

<body>
<input id="txt" type="text" value="请输入关键词">
<button id="copy">点击复制文本</button>
<textarea id="txtarea"></textarea>

<script>

// ie 和 chorme 的event 的函数是一个全局对象。所以可以直接使用event.

// 火狐就是放在函数的的第一个参数

window.onload = function () {
  var txt = document.getElementById('txt');
  var copy = document.getElementById('copy');
  var txtarea = document.getElementById('txtarea');

  txt.focus(); // 获得焦点方法

  txt.onfocus = function () {
    if (this.value === "请输入关键词") {
      txt.value = "";
   }
  };

txt.onblur = function () {
if (this.value === "") {
  txt.value = "请输入关键词";
}
};

copy.onclick = function () {
  txt.select(); // select() 全选 focus()、blur()、select()交互的时候才能操作
  document.execCommand("copy"); //执行复制命令 已测试ie7以上都支持
  alert("已经复制成功了");
};

};

</script>

</body>
</html>

原文地址:https://www.cnblogs.com/Shinnosuke/p/5694116.html