javascript - document.execCommand('copy') 命令在 Chrome 中不起作用
问题描述
HTML
<input type="text" id="clipboard">
<button class="share-button">share</button>
JS
text = 'text to be copied';
document.querySelector('.share-button').addEventListener('click', () => {
var element = document.querySelector('#clipboard');
element.setAttribute("value", text);
console.log(element.value);
element.select();
document.execCommand('copy');
});
CSS
#clipboard {
position: absolute;
visibility: hidden;
}
我正在尝试将文本复制到剪贴板,但我不明白我的代码有什么问题。我从 MDN 文档中复制了代码。
当我做这些事情时它不起作用
#clipboard {
position: absolute;
}
// or
#clipboard {
visibility: hidden
}
// or
#clipboard {
display: none
}
解决方案
const share_btn = document.querySelector('.share-button');
function copy_to_clipboard(stritem){
const el = document.createElement('textarea');
el.value = stritem;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
window.alert('Successfully copied to your clipboard!');
}
text = 'text to be copied';
share_btn.addEventListener('click', ()=>{copy_to_clipboard(text);});
<button class="share-button">share</button>
推荐阅读
- javascript - 使用循环推送到一个数组,该数组是 Map 中的一个值
- android - Android性能优化调度延迟
- javascript - 如果搜索包含括号或方括号,RegEx 匹配将返回 undefined
- ruby-on-rails - 门卫外键违反访问授权
- php - 用 php rand() 数字填充 html 表
- python - 我们如何得到这个按位运算的答案?
- google-chrome-extension - 有没有办法从后台脚本获取浏览器信息,包括版本号?
- python - python - 属性 x 是一个属性对象,它为这个私有变量提供接口
- javascript - 用 jest 测试回调函数
- ios - 如何从来自后端的 mp3 文件 URL 获取元数据以显示 ArtWork Image?