我正在谷歌上查看一个脚本来复制一个输入字段,这就出现了:
https://jsfiddle.net/9q3c1k20/
我的例子:
document.getElementById("copy-text").onclick = function() {
this.select();
document.execCommand('copy');
alert('This is a test...');
}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-1.11.0.js"></script>
</head>
<body>
<input id="copy-text" type="text" value="Select a part of this text!">
</body>
</html>
&#13;
答案 0 :(得分:1)
在解析文档正文(和输入元素)之前,正在运行选择#copy-text
的脚本。将脚本移动到正文的底部:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-1.11.0.js"></script>
</head>
<body>
<input id="copy-text" type="text" value="Select a part of this text!">
<script>
document.getElementById("copy-text").onclick = function() {
this.select();
document.execCommand('copy');
alert('This is a test...');
}
</script>
</body>
</html>
但是将脚本放在单独的.js文件中并将其赋予defer
属性更为优雅:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-1.11.0.js"></script>
<script src="myscript.js" defer></script>
</head>
<body>
<input id="copy-text" type="text" value="Select a part of this text!">
</body>
</html>