js剪切板

copyToClipboard: function (text) {
  return new Promise(function (resolve) {
    var value = String(text == null ? '' : text);

    // 更稳健的特性检测,避免直接访问导致报错
    var clipboard = null;
    try {
      clipboard = (typeof navigator !== 'undefined' && navigator && navigator.clipboard) ? navigator.clipboard : null;
    } catch (e) {
      clipboard = null;
    }

    // 优先使用异步 API(若可用)
    if (clipboard && typeof clipboard.writeText === 'function') {
      clipboard.writeText(value).then(function () {
        resolve(true);
      }).catch(function () {
        resolve(fallbackCopy(value));
      });
      return;
    }

    // 回退方案
    resolve(fallbackCopy(value));

    function fallbackCopy(v) {
      try {
        var textarea = document.createElement('textarea');
        textarea.value = v;
        textarea.setAttribute('readonly', '');
        textarea.style.position = 'fixed';
        textarea.style.top = '-9999px';
        textarea.style.left = '0';
        textarea.style.width = '1px';
        textarea.style.height = '1px';
        document.body.appendChild(textarea);

        textarea.focus();
        textarea.select();
        // 兼容 iOS 的选择范围
        try { textarea.setSelectionRange(0, textarea.value.length); } catch (e) {}

        var ok = false;
        try {
          ok = document.execCommand('copy');
        } catch (e) {
          ok = false;
        }

        document.body.removeChild(textarea);
        return ok;
      } catch (e) {
        return false;
      }
    }
  });
},
function showToast(message, duration) {
  duration = typeof duration === 'number' ? duration : 2000;

  var toast = document.createElement('div');
  toast.textContent = message;
  toast.style.position = 'fixed';
  toast.style.left = '50%';
  toast.style.bottom = '12%';
  toast.style.transform = 'translateX(-50%)';
  toast.style.maxWidth = '80%';
  toast.style.padding = '10px 14px';
  toast.style.background = 'rgba(0,0,0,0.75)';
  toast.style.color = '#fff';
  toast.style.fontSize = '14px';
  toast.style.lineHeight = '1.4';
  toast.style.borderRadius = '6px';
  toast.style.zIndex = '2147483647';
  toast.style.pointerEvents = 'none';
  toast.style.opacity = '0';
  toast.style.transition = 'opacity 200ms ease';

  document.body.appendChild(toast);

  requestAnimationFrame(function () {
    toast.style.opacity = '1';
  });

  setTimeout(function () {
    toast.style.opacity = '0';
    toast.addEventListener('transitionend', function () {
      if (toast && toast.parentNode) {
        toast.parentNode.removeChild(toast);
      }
    }, { once: true });
  }, duration);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值