我需要一个小脚本,将允许我复制文本字符串点击没有按钮。
我找到了这个密码:
function copy(that){
var inp =document.createElement('input');
document.body.appendChild(inp)
inp.value =that.textContent
inp.select();
document.execCommand('copy',false);
inp.remove();
}代码在单击时复制文本,但不显示任何消息。我想修改它一点,所以当用户单击文本时,它将被复制,并显示一条2-3秒的弹出式消息(然后它应该自行解除),说明文本已被复制到剪贴板。有谁知道如何用这种方式修改代码吗?
<p onclick="copy(this)">example text</p> --它就是这样识别要复制哪些代码的。
发布于 2019-05-04 14:48:11
我希望这个功能能帮助你:
copy(){
input = $(this).val();
document.execCommand('copy',false,input);
$(this).next('text copied');
setTimeout(function(){$(this).next().remove();}, 2000);
}请记住,您必须创建一个标签,其中您将显示消息旁边的输入标签。
发布于 2019-05-04 16:59:16
嘿,有一个完整的例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="text" onclick="copy(this)" value="malek gorchene"></input>
<!-- this p is for the notification -->
<p></p>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script type="text/javascript">
function copy(elem){
input = $(elem).val();
elem.select();//Select the text in the input element
document.execCommand('copy');//copy it
$(elem).next().text('text copied');
setTimeout(function(){$(elem).next().text('');}, 2000);//
}
</script>
</html>发布于 2019-05-04 18:10:17
嘿,这是第一个问题,但我不明白第二个问题:
function copy(elem){
if($(elem).text()){
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = $(elem).text();
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}else{
input = $(elem).val();
elem.select();//Select the text in the input element
document.execCommand('copy');//copy it
}
$(elem).next().text('text copied');
setTimeout(function(){$(elem).next().text('');}, 2000);//
}<input type="text" onclick="copy(this)" value="click me"></input>
<p></p>
<p onclick="copy(this)">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<!-- this p is for the notification -->
<p></p>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
https://stackoverflow.com/questions/55983215
复制相似问题