如何实现点击图片时将指定文本复制到剪贴板?
点击图片复制文本到剪贴板实现方案
原实现代码
JavaScript部分
function myFunction() { var copyText = document.getElementById("myInput"); copyText.select(); document.execCommand("copy"); alert("Copied the text: " + copyText.value); }
HTML部分
<input type="text" value="text which you want copy" id="myInput" hidden> <img src="nameofimage.jpg" onclick="myFunction()"></img>
原代码失效原因
document.execCommand方法已被现代浏览器官方弃用,多数新版浏览器已不再支持该接口- 带有
hidden属性的input元素无法被正常选中读取内容,导致复制操作无响应
可行解决方案
修正后JavaScript代码
async function myFunction() { const targetText = document.getElementById("myInput").value; try { await navigator.clipboard.writeText(targetText); alert("已复制文本:" + targetText); } catch (e) { console.error("复制失败:", e); } }
修正后HTML代码
<input type="text" value="需要复制的文本内容" id="myInput" style="position: absolute; opacity: 0; pointer-events: none;"> <img src="nameofimage.jpg" onclick="myFunction()" style="cursor: pointer;">
优化说明
- 采用标准Clipboard API
navigator.clipboard.writeText实现复制操作,兼容所有主流现代浏览器 - 将input元素改为透明绝对定位布局,既不在页面可见,也能正常读取内容
- 新增点击复制失败的异常捕获逻辑,方便排查问题
- 图片新增手型光标样式,提示用户可点击交互
内容的提问来源于stack exchange,提问作者Warren Rosenfeld
相关产品推荐
相关产品推荐

