如何将div内的文本复制到剪贴板?我有一个div,需要添加一个链接,将文本添加到剪贴板。有解决办法吗?
<p class="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>
<a class="copy-text">copy Text</a>
在我点击复制文本,然后我按Ctrl + V,它必须被粘贴。
大多数建议的答案都会创建一个额外的临时隐藏输入元素。因为现在大多数浏览器都支持div内容编辑,所以我提出了一个解决方案,它不创建隐藏元素,保留文本格式,并使用纯JavaScript或jQuery库。
下面是一个使用我能想到的最少代码行的极简框架实现:
//Pure javascript implementation:
document.getElementById("copyUsingPureJS").addEventListener("click", function() {
copyUsingPureJS(document.getElementById("copyTarget"));
alert("Text Copied to Clipboard Using Pure Javascript");
});
function copyUsingPureJS(element_id) {
element_id.setAttribute("contentEditable", true);
element_id.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
element_id.focus();
document.execCommand("copy");
element_id.removeAttribute("contentEditable");
}
//Jquery:
$(document).ready(function() {
$("#copyUsingJquery").click(function() {
copyUsingJquery("#copyTarget");
});
function copyUsingJquery(element_id) {
$(element_id).attr("contenteditable", true)
.select()
.on("focus", function() {
document.execCommand('selectAll', false, null)
})
.focus()
document.execCommand("Copy");
$(element_id).removeAttr("contenteditable");
alert("Text Copied to Clipboard Using jQuery");
}
});
#copyTarget {
width: 400px;
height: 400px;
border: 1px groove gray;
color: navy;
text-align: center;
box-shadow: 0 4px 8px 0 gray;
}
#copyTarget h1 {
color: blue;
}
#copyTarget h2 {
color: red;
}
#copyTarget h3 {
color: green;
}
#copyTarget h4 {
color: cyan;
}
#copyTarget h5 {
color: brown;
}
#copyTarget h6 {
color: teal;
}
#pasteTarget {
width: 400px;
height: 400px;
border: 1px inset skyblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="copyTarget">
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
<strong>Preserve <em>formatting</em></strong>
<br/>
</div>
<button id="copyUsingPureJS">Copy Using Pure JavaScript</button>
<button id="copyUsingJquery">Copy Using jQuery</button>
<br><br> Paste Here to See Result
<div id="pasteTarget" contenteditable="true"></div>
HTML:
// you need bootstrap(js && css) and JQuery(js)
<span class="text-copy" value="your-text">text</span>
CSS:
.text-copy {
cursor: pointer;
color: #0d6efd;
text-decoration: underline;
}
.text-copy:hover {
color: #1b6be4;
}
JS(使用JQuery):
$(document).ready(function() {
var elements = $('.copy-text');
for(let i = 0; i < elements.length; i++) {
const element = $(elements[i]);
element.attr('data-toggle', 'tooltip')
.attr('data-placement', 'top')
.attr('title', `Tab to copy "${element.attr('value')}"`);
}
$('[data-toggle="tooltip"]').tooltip();
$('.text-copy').click(function() {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(this).attr('value')).select();
document.execCommand("copy");
$temp.remove();
});
});
$(document).ready(async function() {
var elements = $('.text-copy');
for(let i = 0; i<elements.length; i++) {
const element = $(elements[i]);
element.attr('data-toggle', 'tooltip')
.attr('data-placement', 'top')
.attr('title', `Tab to copy "${element.attr('value')}"`);
}
$('[data-toggle="tooltip"]').tooltip();
$('.text-copy').click(function() {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(this).attr('value')).select();
document.execCommand("copy");
$temp.remove();
});
});
body {
display: grid;
justify-content: center;
}
.text-copy {
cursor: pointer;
color: #0d6efd;
text-decoration: underline;
}
.text-copy:hover {
color: #1b6be4;
}
<html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<h2 class="text-copy" value="your copy text">your text</h2>
<br>
<h4>paste here</h4>
<input type="text">
</body>
</html>
我刚才正在做,我只是想知道有没有比我更好的方法,但是没有。
你可以使用我的代码,它复制文本并显示一个工具提示。
Head
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/remixicon@2.2.0/fonts/remixicon.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Body
<div class="alert alert-primary alert-dismissible mb-0 py-1" role="alert" id="liveAlert">
<div class="container d-flex justify-content-between">
<button type="button" class=" btn align-self-center ms-4 copytext" data-bs-toggle="tooltip" data-bs-placement="top" title=""><strong>Good news!</strong> You just got 10% off, use your coupon <span class="fw-bold bg-secondary text-white px-2 maintext">store10off</span>. <i class="ri-file-copy-line"></i></button>
<button type="button" class="btn align-self-center" data-bs-dismiss="alert" aria-label="Close"><strong class="fw-bold fs-4"><i class="ri-close-fill"></i></strong></button>
</div>
</div>
函数
<script>
$('.copytext').click(function(){
var thistooltip = $(this);
var thistext = $(this).children('.maintext').text();
navigator.clipboard.writeText(thistext);
$(this).attr('title','copied');
setTimeout(function(){$(thistooltip).tooltip("toggle");}, 800);
});
</script>
大多数建议的答案都会创建一个额外的临时隐藏输入元素。因为现在大多数浏览器都支持div内容编辑,所以我提出了一个解决方案,它不创建隐藏元素,保留文本格式,并使用纯JavaScript或jQuery库。
下面是一个使用我能想到的最少代码行的极简框架实现:
//Pure javascript implementation:
document.getElementById("copyUsingPureJS").addEventListener("click", function() {
copyUsingPureJS(document.getElementById("copyTarget"));
alert("Text Copied to Clipboard Using Pure Javascript");
});
function copyUsingPureJS(element_id) {
element_id.setAttribute("contentEditable", true);
element_id.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
element_id.focus();
document.execCommand("copy");
element_id.removeAttribute("contentEditable");
}
//Jquery:
$(document).ready(function() {
$("#copyUsingJquery").click(function() {
copyUsingJquery("#copyTarget");
});
function copyUsingJquery(element_id) {
$(element_id).attr("contenteditable", true)
.select()
.on("focus", function() {
document.execCommand('selectAll', false, null)
})
.focus()
document.execCommand("Copy");
$(element_id).removeAttr("contenteditable");
alert("Text Copied to Clipboard Using jQuery");
}
});
#copyTarget {
width: 400px;
height: 400px;
border: 1px groove gray;
color: navy;
text-align: center;
box-shadow: 0 4px 8px 0 gray;
}
#copyTarget h1 {
color: blue;
}
#copyTarget h2 {
color: red;
}
#copyTarget h3 {
color: green;
}
#copyTarget h4 {
color: cyan;
}
#copyTarget h5 {
color: brown;
}
#copyTarget h6 {
color: teal;
}
#pasteTarget {
width: 400px;
height: 400px;
border: 1px inset skyblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="copyTarget">
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
<strong>Preserve <em>formatting</em></strong>
<br/>
</div>
<button id="copyUsingPureJS">Copy Using Pure JavaScript</button>
<button id="copyUsingJquery">Copy Using jQuery</button>
<br><br> Paste Here to See Result
<div id="pasteTarget" contenteditable="true"></div>