scenario

Interviewer: Please implement A string paste to the sticky board small A: What? Paste board, used to use library ah, not how to understand, or you hint? Interviewer: All right……

Train of thought

  1. Create a TEXtarea DOM and fill STR into value. And select it
  2. Run the copy command
  3. Add the selected content to Selection

The problem solving code

const copyToClipboard = str= > {

  const el = document.createElement('textarea')

  el.value = str

  el.setAttribute('readonly'.' ')

  el.style.position = 'absolute'

  el.style.left = '-9999px'

  document.body.appendChild(el)

  const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false

  el.select()

  document.execCommand('copy')

  document.body.removeChild(el)

  if(selected) {

    document.getSelection().removeAllRanges()

    document.getSelection().addRange(selected)

  }

}

Copy the code

tips

Document.execcommand, Document.getSelection (), document.execcommand, document.getSelection()

  1. Actually, I don’t think so
  2. If you’re in the editor domain, you might, because the editor domain doesn’t know too much about execCommand and getSelection
  3. In fact, the whole problem is not particularly difficult to finish, you can think clearly