javascript - 在 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>
解决方案
'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>
推荐阅读
- rsync - rsync - 文件的权限是否会使用 -avp 从 root 用户更改为普通用户
- python - 将数据加载到 Catboost 池对象中
- c# - 如何在启动文件上配置基于属性的路由,而不是在 asp.net core mvc 中的控制器操作上使用属性
- flutter - 在 firestore 中显示具有动态添加字段的子集合时出现问题
- javascript - 反应本机样式表颜色不动态更新
- sql - 在 Access 2016 中按组查询返回具有连续日期的记录
- c# - 调用类方法作为参数
- r - 将列中的最高值和第二高值替换为其中值
- html - 如何设置填充但保持元素响应?
- visual-studio-code - VS Code 光标一直进入改写模式