js复制和粘贴内容

admin
2022-03-19 / 0 评论 / 428 阅读 / 正在检测是否收录...

复制-将指定内容添加到粘贴板

/**
 * copyToClip
 * @param content
 * @param callback
 */
export const copyToClip = (content: string, callback?: () => void) => {
  var aux = document?.createElement?.('input');
  aux?.setAttribute?.('value', content);
  document?.body?.appendChild?.(aux);
  aux?.select();
  document?.execCommand('copy');
  document?.body?.removeChild?.(aux);
  return callback?.();
};

粘贴 js不能直接读取粘贴板内容,下面的代码在多数环境下不生效

const text = await navigator?.clipboard?.readText?.();

我们采取变通的方案来处理。
1、在页面中添加一个input输入框,将其绝对定位到页面中不可见的位置

<input
  type='text'
  id='text-all'
  key='text-all'
  onPaste={(e) => handlePaste(e)}
  style={{ position: 'absolute', top: -10000, zIndex: 10000 }}
/>

监听到ctrl-v事件时,先让上面的input获得焦点,再手动触发他的paste事件,这时input会填充粘贴板中的内容

const hideInput: HTMLInputElement = document.getElementById('text-all') as any;
hideInput?.focus();
hideInput?.dispatchEvent(new Event('paste', { bubbles: true }));

给这个input添加onPaste事件,在事件处理函数中获取input的内容,或者获取粘贴板的内容

const clipboardData = e?.clipboardData || e.originalEvent?.clipboardData;
0

评论 (0)

取消