Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS复制数据到剪切板 #10

Open
wqhui opened this issue Oct 22, 2020 · 0 comments
Open

JS复制数据到剪切板 #10

wqhui opened this issue Oct 22, 2020 · 0 comments

Comments

@wqhui
Copy link
Owner

wqhui commented Oct 22, 2020

核心方法是执行document.execCommand('copy'),不过该方法需要一个可编辑元素,所以我们要先创建一个input或者是textarea,然后将数据赋给可编辑元素,选中值并且设置焦点,然后执行。

const copyDataToClipboard = (data) => (element) => {
  element.value = data
  element.select()
  element.focus()
  document.execCommand('copy')
}

function executeOnTempElement (targetDom, callback) {
  var eTempInput = document.createElement('textarea')
  eTempInput.style.width = '1px'
  eTempInput.style.height = '1px'
  eTempInput.style.top = '0px'
  eTempInput.style.left = '0px'
  eTempInput.style.position = 'absolute'
  eTempInput.style.opacity = '0.0'
  targetDom = targetDom || document
  targetDom.appendChild(eTempInput)
  try {
    callback(eTempInput)
  } catch (err) {
    console.warn(' Browser does not support document.execCommand(\'copy\') for clipboard operations')
  }
}

//send
function sendToClipboard () {
  executeOnTempElement(ducument, copyDataToClipboard('hello world'))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant