You need to enable JavaScript to run this app. 如何修改剪贴板复制代码实现仅复制双列表格的第二列内容
优惠活动
大模型
产品
解决方案
定价
更多

如何修改剪贴板复制代码实现仅复制双列表格的第二列内容

适配双列表格的点击复制实现方案

一、完整修改后代码

HTML结构

<div class="container">
  <div class='copied'></div>
  <!-- 双列表格结构 -->
  <table class="copy-table">
    <tr>
      <td>Sometext column 1</td>
      <td>Some text column 2</td>
    </tr>
    <tr>
      <td>测试第一列1</td>
      <td>要复制的第二列内容1</td>
    </tr>
    <tr>
      <td>测试第一列2</td>
      <td>要复制的第二列内容2</td>
    </tr>
  </table>
</div>

JavaScript代码

$(function() {
  // 绑定表格行点击事件
  $('.copy-table tr').click(function() {
    // 获取当前行第二列的文本内容,eq索引从0开始计数,第二列对应索引1
    const copyText = $(this).find('td:eq(1)').text().trim();
    // 创建临时input元素用于选中复制
    const tempInput = $('<input>').val(copyText).appendTo('body').select();
    document.execCommand('copy');
    // 移除临时元素不影响原有页面结构
    tempInput.remove();
    // 保留原有复制成功提示逻辑
    $(".copied").text("Copied to clipboard").show().fadeOut(2500);
  });
});

CSS样式

.container {
  max-width: 45rem;
  background: #f7f7f7;
  margin: 2rem auto;
  position: relative;
  padding: 2rem;
}
/* 新增表格基础样式 */
.copy-table {
  width: 100%;
  border-collapse: collapse;
}
.copy-table tr {
  cursor: pointer;
  background: #fff;
}
.copy-table tr td {
  border: 1px solid #eee;
  padding: 0.8rem 0.5rem;
}
.copy-table tr:hover {
  background: #f0f0f0;
}
/* 原有提示样式保留,调整位置适配表格场景 */
.copied {
  position: absolute;
  background: #6ce890;
  color: #000;
  padding: 0.2rem;
  font-weight: bold;
  z-index: 99;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
  display: none;
  font-size: .8rem;
}

二、核心改动说明

  • 将原有的单input复制结构替换为双列表格,新增copy-table类作为事件绑定标识
  • 点击事件绑定到表格行,自动获取当前点击行第二列的文本内容作为复制目标
  • 新增临时input元素完成文本选中、复制逻辑,执行结束后自动销毁临时元素
  • 保留原有复制成功的提示效果,调整提示框为水平居中适配表格宽度

内容的提问来源于stack exchange,提问作者Austen Robinson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 11:54:02