主要实现的功能是点击复制链接按钮,就会自动复制一个链接,用户可直接到别处粘贴
safari直接看下边插件部分
直接用js实现(不兼容safari)
下边代码是基于vue开发的部分代码,但主要代码是通用的
<button class="shareButton" @click="copyLink(item)">复制链接</button>
<!-- js部分实现需要一个input或者textarea,不可使用display:none或者在元素中设置hidden属性,所以需要通过设置透明度和定位将它隐藏,并且设置z-index避免点到它 -->
<!-- 或者动态创建一个textarea,用完后再remove掉 -->
<textarea v-model="shareLink" id="hideText"></textarea>
copyLink (activityItemInfo) {
this.shareLink = activityItemInfo.activityUrl
this.$nextTick(() => {
// 动态创建一个input
// var tag = document.createElement('input');
// tag.setAttribute('id', 'hideText');
// tag.value = text;
// document.getElementsByTagName('body')[0].appendChild(tag);
// document.getElementById('hideText').select();
// document.execCommand('copy');
// document.getElementById('hideText').remove();
var text = document.querySelector('#hideText')
text.focus() // 获取焦点
text.select() // 选中内容
document.execCommand('copy') // 执行复制
text.blur() // 失去焦点(不然在手机上会弹出输入法)
this.$toast('复制成功')
})
}
#hideText {
opacity: 0;
position: absolute;
z-index: -9999;
}
使用clipboard插件
安装
npm install clipboard --save
使用
<!-- data-clipboard-action可以设置位copy或者cut ;data-clipboard-text为需要复制的内容-->
<button class="copyBtn" data-clipboard-action="copy" :data-clipboard-text="item.activityUrl" @click="copyLink(item)">复制链接</button>
或者可以直接复制文本框内的内容
<textarea id="bar">Mussum ipsum cacilds...</textarea>
<button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">
Cut to clipboard
</button>
import Clipboard from 'clipboard';
copyLink (index) {
var clipboard = new Clipboard('.copyBtn')
clipboard.on('success', e => {
this.$toast('复制成功')
clipboard.destroy()
})
clipboard.on('error', e => {
clipboard.destroy()
})
}