我使用以下代码自动复制所选文本:
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('discount code has been copied);
setTimeout(function(){$(elem).next().text('');}, 2000);//
}
`
我对该代码有两个问题:
如果我想在我的帖子中使用它,我将添加以下代码:
<p class="kod-rabatowy" onclick="copy(this)">example text that needs to be copied</p>
在文本编辑器中。问题是整个脚本仅适用于<p>
标签 - 我真的需要在同一行中显示文本。我怎样才能让它与其他标签一起使用(<b>
就完美了)?- 如何向整个脚本添加类,以便我可以设置文本样式以表明代码已被复制?在这里您可以看到它现在是如何工作的:http://test2.gromocje.pl/?p=21 (点击“测试”按钮,您将复制它)。
最佳答案
看起来工作正常(我不知道 WordPress 帖子):https://jsbin.com/yoropunebu/edit?html,css,js,output
我还添加了您想要的类(class):
$(elem).next().addClass("copied-response").text('discount code has been copied');
关于javascript - 如何使代码与其他标签一起使用并向其添加类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55995758/