You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript复制type为hidden的input元素的值?

如何用JavaScript复制type为hidden的input元素的值

type为hidden的input元素无法直接通过select()方法选中内容,因此需要通过变通方式实现复制功能,以下是两种可行的实现方案:

方案一:临时修改input类型

先将hidden的input临时改为text类型,完成复制后再改回hidden,同时配合样式临时让它脱离可视区域(避免部分浏览器无法选中):

HTML

<input type="hidden" value="要复制的内容" id="hiddenInput">
<button id="copyBtn">复制内容</button>

JavaScript

document.getElementById('copyBtn').addEventListener('click', function() {
  const hiddenInput = document.getElementById('hiddenInput');
  // 保存原类型并临时修改
  const originalType = hiddenInput.type;
  hiddenInput.type = 'text';
  hiddenInput.style.position = 'absolute';
  hiddenInput.style.left = '-9999px';
  
  hiddenInput.select();
  document.execCommand('copy');
  
  // 恢复元素原状态
  hiddenInput.type = originalType;
  hiddenInput.style.removeProperty('position');
  hiddenInput.style.removeProperty('left');
  
  this.textContent = '已复制';
});

方案二:创建临时元素复制

创建一个临时的input元素,将hidden input的值赋给它,完成复制后移除临时元素:

HTML

<input type="hidden" value="要复制的内容" id="hiddenInput">
<button id="copyBtn">复制内容</button>

JavaScript

document.getElementById('copyBtn').addEventListener('click', function() {
  const hiddenInput = document.getElementById('hiddenInput');
  const tempInput = document.createElement('input');
  
  tempInput.value = hiddenInput.value;
  tempInput.style.position = 'absolute';
  tempInput.style.left = '-9999px';
  document.body.appendChild(tempInput);
  
  tempInput.select();
  document.execCommand('copy');
  
  document.body.removeChild(tempInput);
  this.textContent = '已复制';
});

补充:类隐藏的text类型input复制

如果你的场景中是用display: none类隐藏的text类型input(如下方参考示例),可以直接使用select()方法完成复制:

参考示例代码

HTML

<input class="d-none" type="text" value="my name is vikram" id="idCopyReferralLink">
<a href="javascript:void(0)" class="clsCopyClipboardText" id="lnkReferralUrlCopySigned">COPY LINK</a>

JavaScript

$(document).ready(function(){
    $(".clsCopyClipboardText").on("click", function() {
        var input = document.getElementById("idCopyReferralLink");
        input.select();
        document.execCommand('copy');
        input.blur();
        $(this).html("COPIED");
    });
});

内容的提问来源于stack exchange,提问作者vikram kuldeep

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:35:26