首页 > 解决方案 > 在 JavaScript 中复制元素内容

问题描述

我正在尝试编写可以复制 a 内容的 JS 代码,td同时显示某种通知,让用户知道某些内容已复制到剪贴板。我尝试了以下代码并且复制到剪贴板工作正常,但通知从未奏效。我应该怎么办?

PHP 和 HTML:

echo "<td onClick='copy(this),selectThis(this)'> " . $row['email'] . "</td>";

JS:

<script type="text/javascript">
    function copy(that){
        var inp =document.createElement('input');
        document.body.appendChild(inp)
        inp.value =that.textContent
        inp.select();
        document.execCommand('copy',false);
        inp.remove();
    }
    function selectThis(element) {
        document.createElement("input")).style.backgroundColor = "red";
    }
</script>

标签: javascript

解决方案


'use strict';
function copy(that){
 // ...
 notify(that.textContent);
}

function notify(content) {
  let notification = document.createElement('span');
  notification.classList.add('notification');
  notification.textContent = `"${content}" copied`;
  document.body.prepend(notification);
  setTimeout(() => notification.remove(), 4000);
}
.notification {
  border: solid 1px green;
  padding: 5px;
  animation-name: fade;
  animation-duration: 4s;
  animation-iteration-count: 2;
  animation-direction: alternate;
 }
 
@keyframes fade {
  from { opacity:0; }
  to { opacity:1; }
}
<p onclick="copy(this)" id="element" >Click here to copy this text (figuratively).</p>


推荐阅读