js實現點擊按鈕復制文本功能


最近項目活動中用到復制文本功能,發現在chrome中之前的clipboard的demo失效了,查了下發現是因為版本升級導致的。最新用法如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.copy-link{
width: 478px;
height: 96px;
background: #333;
margin: 28px auto 0;
font-size: 32px;
color: #ac6c44;
line-height: 86px;
text-align: center;
cursor: pointer;
}
</style>
</head>
<body>
<div id="link" class="link-url indent">即將被復制的內容</div>
<div onselectstart="return false" class="copy-link" data-clipboard-action="copy" data-clipboard-target="#link">復制鏈接</div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.js"></script>
<script src="clipboard.js"></script>
<script>
$('.copy-link').click(function(){
var clipboard = new ClipboardJS('.copy-link');
clipboard.on('success', function(e) {
console.log(e);
alert('復制成功');
});
clipboard.on('error', function(e) {
alert('復制失敗');
});
});
</script>
</html>
 
另附上另一種復制方式:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="link-box">
<div id="link-box">
<div class="link-con">
Hello World!
</div>
<div class="link-url">您的專屬鏈接:</div>
<div class="link-url indent">hello world!!!</div>
</div>
<div onselectstart="return false" class="copy-link">復制鏈接</div>
</div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.js"></script>
<script src="clipboard.js"></script>
<script>
$('.copy-link').click(function(){
copyTxt('link-box');
});

// 復制功能
function copyTxt(con) {
const range = document.createRange();
range.selectNode(document.getElementById(con));
const selection = window.getSelection();
if(selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
alert("復制成功!");
}
</script>
</html>
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM