首页 > 解决方案 > 如何在表格中动态修复工具提示消息ID

问题描述

在表中,我正在尝试使用复制的文本工具提示消息创建一个 Onclick 文本复制器。实际上,我已经成功地创建了一个单独的 id 文本复制器,但是我遇到了单独的工具提示消息的问题,它不适合不创建单独的动态 id,这就是原因。那么如何解决这个问题以创建自定义工具提示动态 id?

function textCopied(that){
  var inp =document.createElement('input');
  document.body.appendChild(inp)
  inp.value =that.textContent
  inp.select();
  document.execCommand('copy',false);
  inp.remove();

  document.getElementById("custom-tooltip").style.display = "inline";
  setTimeout( function() {
      document.getElementById("custom-tooltip").style.display = "none";
  }, 1000);
};
.container {
    display: flex;
    justify-content: center;
    height: 100vh;
}
.copybutton{
    background-color: #fff;
    border: 0;
    outline: 0;
    cursor: pointer;
    opacity: 1;
    position: absolute;
    width: 40px;
    height: 40px;
    z-index: 9;
    border-radius: 24px;
    }
.button-tooltip-container {
    display: flex;
    align-items: center;
    margin-top: 16px;
    min-height: 30px;
}
#custom-tooltip {
    position: absolute;
    display: none;
    margin-left: 40px;
    padding: 5px 12px;
    background-color: #000000df;
    border-radius: 4px;
    color: #fff;
} 
table tbody tr td{
    padding: 5px 40px;
}
<div class="container">
    <table>
        <thaed>
            <tr>
                <th>ID</th>
            </tr>
        </thaed>
        <tbody>
            <tr>
                <td>
                    <div class="button-tooltip-container">
                        <span title="Click & Copy This ID" onclick="textCopied(this);" class="copybutton">94426</span>
                        <span id="custom-tooltip">copied!</span>
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <div class="button-tooltip-container">
                        <span title="Click & Copy This ID" onclick="textCopied(this);" class="copybutton">94425</span>
                        <span id="custom-tooltip">copied!</span>
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <div class="button-tooltip-container">
                        <span title="Click & Copy This ID" onclick="textCopied(this);" class="copybutton">94424</span>
                        <span id="custom-tooltip">copied!</span>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>
</div>

标签: javascriptcss

解决方案


我建议您将“#custom-tooltip”更改为一个类“.custom-tooltip”,然后通过靠近单击的元素搜索要显示的正确工具提示,如下所示:

function textCopied(el){
  var inp =document.createElement('input');
  document.body.appendChild(inp);
  inp.value = el.textContent;
  inp.select();
  document.execCommand('copy',false);
  inp.remove();
  var tt = el.parentNode.querySelector(".custom-tooltip");
  tt.style.display = "inline";
  setTimeout( function() {
    tt.style.display = "none";
  }, 1000);
};

推荐阅读