1.需求
点击实现复制文本内容
2.实现效果

HTML代码:
<template>
<div>
<div style="background-color: #f4f4f4;margin:50px 0 0 460px;width:500px;height:300px;">
<el-input v-model="content"></el-input>
<p>{{ copytext }}</p>
<el-button type="text" @click="copyText(copytext)">复制</el-button>
</div>
</div>
</template>
JavaScript代码:
<script>
export default {
data () {
return {
content: '',
copytext: 'LYG127836182763'
}
},
methods: {
copyText(copytext) {
const text = document.createElement('textarea'); // 创建节点
text.setAttribute('readonly', 'readonly');
text.value = copytext; // 赋值
document.body.appendChild(text); // 插入节点
text.setSelectionRange(0, text.value.length);
text.select(); // 选中节点
document.execCommand('copy'); // 执行浏览器复制方法
if (document.body.removeChild(text)) {
this.$message({ type: 'success', message: '复制成功' })
} else {
this.$message({ type: 'error', message: '复制失败' })
}
}
}
}
</script>
该博客详细介绍了如何使用Vue和ElementUI组件库,通过HTML与JavaScript代码实现简单的文本内容复制功能。用户只需点击按钮,即可轻松复制页面上的文本。
1343

被折叠的 条评论
为什么被折叠?



