在尝试理解有关如何将文本复制到剪贴板的不同方法方面,我遇到了很多问题。如果有人可以向我解释为什么我的代码不起作用,我将不胜感激。
<!DOCTYPE HTML>
<html dark= "true" style="font-size: 50px;font-family: Roboto, Arial, sans-serif">
<body>
<textarea id="copytext">ROGER</textarea>
<div class="button" id="adadad">
<button onclick="copyS()" id="dlld">
</button>
</div>
<p> </p>
<script type=text/javascript">
function copyS{
clicked = document.getElementById("dlld");
}
if ("dlld" == clicked){
var am1 = document.getElementById("copytext");
document.execCommand("copy");
}
}
</script>
<p> </p>
</body>
</html>
答案 0 :(得分:2)
似乎您需要先select()
来自文本区域的文本。尝试将功能更改为:
function copyS{
var clicked = document.getElementById("dlld");
//if ("dlld" == clicked){ //Not sure you need this
var am1 = document.getElementById("copytext");
am1.select();
document.execCommand("copy");
//}
}
希望有帮助!
答案 1 :(得分:2)
好的,我对您的代码做了一些调整,但是现在应该可以了。
<!DOCTYPE HTML>
<html dark= "true" style="font-size: 50px;font-family: Roboto, Arial, sans-serif">
<body>
<textarea id="copytext">ROGER</textarea>
<div class="button" id="adadad">
<button onclick="copyS()" id="dlld">Copy text</button>
</div>
<p> </p>
<!-- removed the single " at the end of your script tag -->
<script type=text/javascript>
//added () after you declared your function
function copyS(){
clicked = document.getElementById("dlld");
//added .id to clicked. Not sure why you need to do this, but it works now
if ("dlld" == clicked.id){
var am1 = document.getElementById("copytext");
//you need to select before running the .execCommand
am1.select();
document.execCommand("copy");
}
}
</script>
<p> </p>
</body>
</html>
答案 2 :(得分:2)
我已更改您的代码以完成工作。
var copiedText = "";
document.querySelector("button").onclick = function(e) {
copiedText = e.target.previousElementSibling.value;
document.execCommand("copy");
}
document.body.oncopy = function(e) {
event.clipboardData.setData('text/plain', copiedText);
event.preventDefault();
};
body {
font-size: 50px;
font-family: Roboto, Arial, sans-serif;
}
<textarea>ROGER</textarea>
<button>Copy</button>
答案 3 :(得分:0)
尝试
(<button id="demo" onclick="copyToClipboard(document.getElementById('demo').innerHTML)">This is what I want to copy</button>)
(<script>
function copyToClipboard(text) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
</script>)