问题描述
我想制作一个书签,以保存从Array解析的字符串,我正在寻找一种将const cp = 'text'
保存到剪贴板的简单方法。这个问题有什么解决办法吗?在此先感谢:)
解决方法
发布之前先四处看看。这是来自w3schools网站。那里有很多很棒的解释。 https://www.w3schools.com/howto/howto_js_copy_clipboard.asp
function myFunction() {
/* Get the text field */
var copyText = document.getElementById("myInput");
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0,99999); /*For mobile devices*/
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
}
,
我使用以下功能来实现这一目标。
const copyToClipboard = (e) => {
const el = document.createElement('input')
el.value = window.location // I need a string that was located in the url => you should use whatever value you need,and set the input value to that,obviously.
el.id = 'url'
el.style.position = 'fixed'
el.style.left = '-1000px' // otherwise,sometimes,it creates an input element visible on the screen
el.setAttribute('readonly',true) // to prevent mobile keyboard from popping up
document.body.appendChild(el)
el.select()
document.execCommand('copy')
}
,
您可以使用复制事件创建类似的功能
const copyToClipboard = (text) => {
document.addEventListener('copy',function(e) {
e.clipboardData.setData('text/plain',text);
e.preventDefault();
});
document.execCommand('copy');
}
此answer也很有帮助。