<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery 复制功能</title> <link rel="stylesheet" href="css/bootstrap4.5.min.css"> <script src="js/jquery-1.12.4.min.js" type="text/javascript" charset="utf-8"></script> <script src="js/clipboard.min.js" type="text/javascript" charset="utf-8"></script> </head> <body> <style> .share-card { box-shadow: 0px 3px 8px 0 rgba(54, 57, 73, .1); color: #fff; margin: 0 auto; } .share-cardCode { margin: auto; padding: 10px 5px; border: 2px dashed #fff; background-color: transparent; } .share-card .active { margin: auto; padding: 10px 5px; color: #0070ff; border: 2px dashed #0070ff; background: transparent; cursor: auto; } .share-copied { /*opacity: 0;*/ width: 80px; background: #101010; margin: 41px -60px; text-align: center; border-radius: 5px; display: inline-block; padding: 8px 0; position: relative; font: normal normal normal 15px/1 FontAwesome; } .share-copied::before { position: absolute; content: ‘‘; margin: auto; left: 32px; top: -20px; border-right: 10px solid #0000; border-bottom: 10px solid black; border-top: 10px solid transparent; border-left: 10px solid transparent; } .btn:hover { color: #fff !important; } </style> <section> <div class="max-width"> <span id="coupon-code-invalid-reasons"></span> <div class="share-card text-center py-3 w-md-70 w-lg-50 mt-3 mt-md-5" style="background-color: rgba(51, 51, 51, 0.45)"> <div class="share-cardCode mb-3 w-70 w-md-50"> <p class="font-24 mb-0 share-card Code-number" id="copy1">这世界我来了,任凭风暴漩涡</p> </div> <button type="button" id="btns" class="btn w-40 margin-auto mb-0 mb-md-3 color-fff btns" data-toggle="modal" style="background-color:#0070ff;"> 复制 </button> </div> </div> </section> <script type="text/javascript"> var clipboard = new ClipboardJS(".btns", { text: function() { //清除字符串两端的空白 var texts = $(".Code-number").text().trim() return texts; } }) //复制成功 clipboard.on(‘success‘, function(e) { //复制成功 console.log(e); var tootpli = $(‘<div class="share-copied position-absolute"><span class="d-block">copied!</span></div>‘); $(e.trigger).append(tootpli); setTimeout(function() { // 2秒后隐藏 tootpli.remove(); }, 2000); }); clipboard.on(‘error‘, function(e) { }); </script> </body> </html>
效果预览: