一、JavaScript模拟复制功能
1、使用navigator.clipboard API模拟复制操作
此API允许你读取和写入用户的剪贴板数据。
// navigator.clipboard 方法复制
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Text copied to clipboard');
} catch (err) {
console.error('复制失败: ', err);
}
}
// 使用示例
copyToClipboard('Hello, World!');
备注:由于安全和隐私原因,此API只能在安全上下文中运行(即HTTPS或本地服务器),并且在某些情况下可能需要用户交互(例如,点击事件)。
2、创建一个隐藏的可编辑元素(如<textarea>)实现复制功能
function fallbackCopyTextToClipboard(text) {
var textArea = document.createElement("textarea");
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = '-999px';
// 给textArea赋值
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
let successful = document.execCommand('copy');
let msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}
document.body.removeChild(textArea);
}
// 使用示例
fallbackCopyTextToClipboard('Hello, World!');
备注:在使用document.execCommand('copy')时需要注意,这个方法已经被废弃,并且在未来的浏览器版本中可能会被移除。因此,推荐优先使用navigator.clipboard API。
二、vue使用指令实现复制功能
在 Vue.js 中,你可以使用自定义指令(Custom Directive)来实现复制到剪贴板的功能。自定义指令允许你在 DOM 被渲染后执行一些操作,比如触发复制行为。
1、在 Vue 实例中定义一个自定义指令
Vue.directive('copy', {
bind: function (el, binding, vnode) {
el.addEventListener('click', async function () {
try {
// copyToClipboard(binding.value) // navigator.clipboard 方法复制
fallbackCopyTextToClipboard(binding.value) // 创建一个隐藏的可编辑元素(如<textarea>)实现复制功能
} catch (err) {
console.error('Failed to copy: ', err);
}
});
}
});
2、在模板中使用这个自定义指令
<button v-copy="myText">{{myText}}</button>
export default {
data() {
return {
myText: 'Hello, world!'
};
}
};
备注:要复制的内容可以直接写在HTML标签中,也可以像上面一样以变量的方式传入