如何修改JS实现多个<pre>标签内容独立复制到剪贴板
多pre标签绑定独立复制按钮调整方案
你现有代码失效的核心原因是copyFunction里硬编码了只取id为copyCodeOne的元素内容,只要把按钮和对应pre标签的关联逻辑改成动态获取即可,推荐用data-*属性做绑定,适配性最强,具体调整步骤如下:
- 第一步:给每个class为
bla的复制按钮添加data-target自定义属性,属性值填写该按钮对应要复制的<pre>标签的id - 第二步:修改复制函数,通过点击事件对象拿到当前触发点击的按钮,再读取它的
data-target值找到对应的pre标签取内容,不再硬编码固定id - 额外优化:补全临时textarea的隐藏、移除逻辑,避免页面出现多余DOM元素或跳动
调整后完整代码示例
HTML部分
<!-- 第一组 --> <button class="bla" data-target="copyCodeOne">复制代码</button> <pre id="copyCodeOne"> 第一段代码/文本内容 </pre> <!-- 第二组 --> <button class="bla" data-target="copyCodeTwo">复制代码</button> <pre id="copyCodeTwo"> 第二段代码/文本内容 </pre> <!-- 第三组 后续新增组只要按这个格式加即可,不用改JS逻辑 --> <button class="bla" data-target="copyCodeThree">复制代码</button> <pre id="copyCodeThree"> 第三段代码/文本内容 </pre>
JS部分
const copyBtns = document.getElementsByClassName("bla"); for (let i = 0; i < copyBtns.length; i++) { copyBtns[i].addEventListener('click', copyFunction, true); } function copyFunction(e) { // 获取当前点击按钮绑定的目标pre的id const targetPreId = e.currentTarget.getAttribute('data-target'); // 动态取对应pre的文本内容 const copyText = document.getElementById(targetPreId).textContent.trim(); // 创建临时输入域 const textArea = document.createElement('textarea'); // 样式设为不可见,避免页面跳动 textArea.style.cssText = 'position:fixed;opacity:0;top:0;left:0;'; textArea.textContent = copyText; document.body.append(textArea); // 执行复制 textArea.select(); document.execCommand("copy"); // 移除临时DOM textArea.remove(); // 可选:复制成功后的按钮提示 const originalText = e.currentTarget.textContent; e.currentTarget.textContent = '已复制'; setTimeout(() => { e.currentTarget.textContent = originalText; }, 1500); }
如果你不想加自定义属性,且按钮和对应pre标签是固定的相邻同级关系(比如按钮永远紧贴在pre标签前面),也可以直接用DOM导航方法拿内容:
const copyText = e.currentTarget.nextElementSibling.textContent,但这种方式对DOM结构变动非常敏感,后续调整布局很容易失效,优先推荐data属性绑定的方案。
内容的提问来源于stack exchange,提问作者riospereira
相关产品推荐
相关产品推荐

