javascript - jquery 复制到剪贴板,然后在几秒钟后撤消
问题描述
我有以下函数将 div 中的文本复制到剪贴板。3 秒后,我希望它取消选择文本。我无法通过 setTimeout 取消选择 div 中的文本。我试过模糊、触发和点击。有解决办法吗?
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");
setTimeout(function () {
//deslect text on page after a few seconds
$(element_id).trigger("click");
}, 3000);
}
解决方案
为此,您不需要 jQuery。这是您的 jQuery 代码的直接翻译。
const unselect = () => window.getSelection().removeAllRanges()
function copyWithoutJQuery(elementId) {
const el = document.getElementById(elementId)
el.setAttribute('contenteditable', true)
el.addEventListener('focus', () => {
document.execCommand('selectAll', false, null);
document.execCommand('Copy');
el.removeAttribute('contenteditable');
setTimeout(unselect, 3000);
})
el.focus();
const range = document.createRange();
range.selectNodeContents(el);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
推荐阅读
- .net - 微服务 API 网关与微服务机箱
- c - 链接两个目标文件以生成一个二进制文件
- javascript - jQuery单击事件即使单击也不会触发
- php - 无法从 php 页面更新 mysql 表
- ios - 使用 cordova 的 iOS 推送通知。从未收到通知
- python - 更改标量和 numpy 数组的数据类型的更短方法
- python - python中的图表上有很多边
- angular - chartjs + Angular6 不显示图表或任何错误
- python-3.x - 无法下载文件(网页抓取) - OSError [Errorno22] - 无效参数
- php - Symfony 减少一个动作