需求:需要点击按钮,复制<i>标签中的内容到剪切板
1、浏览器提供了copy命令,可以复制选中的内容
document.execCommand("copy")
如果是输入框,可以通过 select() 方法,选中输入框的文本,然后调用 copy 命令,将文本复制到剪切板
但是 select() 方法只对 <input> 和 <textarea> 有效,对于 <i> 就不好使
最后我的解决方案是,在页面中添加一个 <textarea>,然后把它隐藏掉
点击按钮的时候,先把 <textarea> 的 value 改为 <i> 的 innerText,然后复制 <textarea> 中的内容
html:
<style>
.copy{
display:inline-block;
}
#hide-input{
position: absolute;top: 0;left: 0;opacity: 0;z-index: -10;
}
.copy-btn{
width:20px;
height:20px;
cursor:pointer;
}
.substring-id{
overflow: hidden;
text-overflow:ellipsis;
white-space: nowrap;
width:120px;
display:inline-block;
cursor:pointer;
}
</style>
<div class="copy">
<i class="substring-id" title="文本内容文本内容文本内容">文本内容文本内容文本内容</i>
<textarea id="hide-input"></textarea>
<button onclick="clickCopy()" class="copy-btn">复制</button>
</div>
js:
<script>
function clickCopy(){
var input = document.getElementById("hide-input");
var text = document.getElementByClassName("substring-id").innerText;
input.value = text;
input.select();
document.execCommand("copy");
alert('复制成功')
</script>

本文介绍了一种在网页上实现复制<i>标签内文本到剪切板的方法。通过创建并隐藏一个<textarea>元素,当用户点击按钮时,将<i>标签的文本内容赋值给<textarea>,然后使用document.execCommand('copy')命令完成复制操作。
4428

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



