如何解决如何为许多按钮制作这个 copybutton Javascript?
谁能帮忙破解这个Javascript?
const copyButton = document.querySelector('.copyButton');
const copyalert = document.querySelector('.copyalert');
copyButton.addEventListener('click',copyClipboard);
function copyClipboard() {
var copystatus= document.getElementById("randomstatus");
// for Internet Explorer
if(document.body.createTextRange) {
var range = document.body.createTextRange();
range.movetoElementText(copystatus);
range.select();
document.execCommand("copy");
window.getSelection().removeAllRanges();
copyalert.classList.add("show");
setTimeout(function() {copyalert.classList.remove("show")},700);
}
else if(window.getSelection) {
// other browsers
var selection = window.getSelection();
var range = document.createrange();
range.selectNodeContents(copystatus);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("copy");
window.getSelection().removeAllRanges();
copyalert.classList.add("show");
setTimeout(function() {copyalert.classList.remove("show")},700);
}
}
此 javascript 用于复制 <p>
元素内的文本。
我的HTML代码
<p id="randomstatus">Strangers think I'm Quiet. My Friends think I'm outgoing. My best friends kNow that I'm Completely Insane</p>
<button class="copyButton btn" id="copyButton"><i class="fas fa-clipboard"></i> copy</button>
<span class="copyalert">copied!</span>
这非常适合一个人,但我需要复制按钮在我的网页中放置更多次。但我一直卡在这里。请帮帮我。
解决方法
一种基本方法是为每个按钮添加一个 onclick
事件属性,用于调用 copyClipboard()
函数
<button class="copyButton btn" id="copyButton" onclick = 'copyClipboard()'><i class="fas fa-clipboard"></i> Copy</button>
<button class="copyButton btn" id="copyButton1" onclick = 'copyClipboard()'><i class="fas fa-clipboard"></i> Copy</button>
并将您的 JavaScript 脚本更改为此
function copyClipboard() {
var copyalert = document.querySelector('.copyalert');
var copystatus= document.getElementById("randomstatus");
// for Internet Explorer
if(document.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(copystatus);
range.select();
document.execCommand("Copy");
window.getSelection().removeAllRanges();
copyalert.classList.add("show");
setTimeout(function() {copyalert.classList.remove("show")},700);
}
else if(window.getSelection) {
// other browsers
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(copystatus);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("Copy");
window.getSelection().removeAllRanges();
copyalert.classList.add("show");
setTimeout(function() {copyalert.classList.remove("show")},700);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。