1. Function description
Click the button to copy the text content in the div element with one click and paste it.
In order to reflect the paste function, add an input box and paste the content of the precise assignment into the input box.
2. Code implementation
html part
<div style="margin: 50px">
<el-button type="primary" @click="copyClick">点击一键复制</el-button>
<div class="testDiv">
这是一段等待复制的文字这是一段等待复制的文字这是一段等待复制的文字
</div>
<el-input v-model="val" style="width:500px" />
</div>
js part
export default {
data() {
return {
val: ''
}
},
methods: {
copyClick() {
const input = document.createElement('input') // 创建input对象
const testDiv = document.querySelector('.testDiv') // 获取需要复制文字的容器
input.value = testDiv.innerText // 设置复制内容
document.body.appendChild(input) // 添加临时实例
input.select() // 选择实例内容
document.execCommand('Copy') // 执行复制
document.body.removeChild(input) // 删除临时实例
this.$message.success('复制成功!')
}
}
}
3. Effect Demonstration
4. Others
The styles involved in the code are simply defined for demonstration purposes, focusing mainly on the implementation methods of the js part. Welcome for reference.