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

如何使用jQuery复制非输入类DOM元素的文本内容到剪贴板?

核心问题原因

select()方法仅支持<input>、<textarea>这类可编辑表单元素,你要复制的<span>属于普通展示类元素,不支持直接选中操作,所以原有复制逻辑失效。

解决方案1:兼容全浏览器方案(推荐)

通过创建临时隐藏的textarea元素实现复制,兼容所有主流浏览器,无需HTTPS环境:

// 可直接绑定到你的复制触发事件(比如按钮点击事件)
function copyTerraAddress() {
  // 获取目标span的文本内容
  const targetText = jQuery('#terra-wallet-address').text();
  // 创建临时textarea元素
  const tempDom = jQuery('<textarea>');
  // 写入内容并设置为不可见,避免页面闪烁
  tempDom.val(targetText).css({
    position: 'absolute',
    left: '-9999px',
    top: '-9999px',
    opacity: 0
  }).appendTo('body');
  // 选中临时元素内容
  tempDom.select();
  // 执行复制命令
  document.execCommand('copy');
  // 移除临时DOM
  tempDom.remove();
  // 原有复制成功提示逻辑
  jQuery('.copied').text("Copied to clipboard").show().fadeOut(1200);
}

解决方案2:现代浏览器原生Clipboard API方案

代码更简洁,不需要创建临时DOM,但要求站点运行在HTTPS环境(localhost本地开发也支持),适配2018年后发布的所有主流浏览器:

async function copyTerraAddress() {
  try {
    const targetText = jQuery('#terra-wallet-address').text();
    // 调用原生剪贴板API写入内容
    await navigator.clipboard.writeText(targetText);
    jQuery('.copied').text("Copied to clipboard").show().fadeOut(1200);
  } catch (error) {
    // 复制失败降级提示
    jQuery('.copied').text("复制失败,请手动复制内容").show().fadeOut(1200);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:15:05