1、vue指令实现意见复制功能
点击复制会将input中内容复制到粘贴板
html
<input type="text" v-model="currentQueBasicInfo.requestUrl" readonly />
<span class="btn btn-primary" v-copy="currentQueBasicInfo.requestUrl">复制</span>
javascript
directives: {
copy: {
bind(el, {value}) {
el.$value = value; // 用一个全局属性来存传进来的值,因为这个值在别的钩子函数里还会用到
el.handler = () => {
if (!el.$value) {
// 值为空的时候,给出提示,我这里的提示是用的 ant-design-vue 的提示,你们随意
console.log('无复制内容');
return;
}
// 动态创建 textarea 标签
const textarea = document.createElement('textarea');
// 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘,同时将 textarea 移出可视区域
textarea.readOnly = 'readonly';
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
// 将要 copy 的值赋给 textarea 标签的 value 属性
textarea.value = el.$value;
// 将 textarea 插入到 body 中
document.body.appendChild(textarea);
// 选中值并复制
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
const result = document.execCommand('Copy');
if (result) {
alertify.alert("复制成功!");
}
document.body.removeChild(textarea);
};
// 绑定点击事件,就是所谓的一键 copy 啦
el.addEventListener('click', el.handler);
},
// 当传进来的值更新的时候触发
componentUpdated(el, {value}) {
el.$value = value;
},
// 指令与元素解绑的时候,移除事件绑定
unbind(el) {
el.removeEventListener('click', el.handler);
}
}
},
2、jquery版本:手机、pc通用
效果图如下:
![页面如下](https://img-blog.csdnimg.cn/2d3acef5af5446f5a1a06ad859028a9f.jpeg)
![复制后粘贴到控制台效果](https://img-blog.csdnimg.cn/d60149666dff492aae0065eac2a741cd.jpeg)
html:
<div id="target">
sudo xattr -d com.apple.quarantine /Applications/Wpspaster.app
<span class="iconfont icon-fuzhi" id="copy-btn" title="复制"></span>
</div>
css:
#target {
padding: 16px;
overflow: auto;
font-size: 16px;
background-color: #f6f8fa;
border-radius: 3px;
margin: 0;
position: relative;
}
#target:hover #copy-btn {
opacity: 1;
}
#copy-btn {
font-size: 14px;
width: 24px;
height: 24px;
line-height: 24px;
text-align: center;
border-radius: 3px;
border: 1px solid #dce3e8;
background: #f6f8fa;
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
color: #8c92a4;
opacity: 0;
-webkit-transition: 0.3s;
-moz-transition: 0.3s;
-ms-transition: 0.3s;
-o-transition: 0.3s;
transition: 0.3s;
}
#copy-btn:hover {
color: #000000;
}
javascript:
$(document).ready(function () {
$('#copy-btn').on('click', handleCopy)
function handleCopy() {
// 创建range对象
const range = document.createRange();
//获取复制内容的 id 选择器
range.selectNode(document.getElementById('target'));
//创建 selection对象
const selection = window.getSelection();
//如果页面已经有选取了的话,会自动删除这个选区,没有选区的话,会把这个选取加入选区
if (selection.rangeCount > 0) selection.removeAllRanges();
selection.addRange(range); //将range对象添加到selection选区当中,会高亮文本块
document.execCommand('copy'); //复制选中的文字到剪贴板
$('.copySuccess').addClass('showCopySuccess')
setTimeout(() => {
selection.removeRange(range); // 移除选中的元素
$('.copySuccess').removeClass('showCopySuccess')
}, 1500)
}
})