我爱编程

JS的复制功能

2018-04-16  本文已影响0人  付出的前端路

使用原生document.execCommand()方法

方法1 在input 输入框中

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
    <input id="demoInput" value="hello world">
    <button id="btn">点我复制</button>
  </body>
  <script>
    const btn = document.querySelector('#btn');
    btn.addEventListener('click', () => {
      const input = document.querySelector('#demoInput');
      input.select();
      if (document.execCommand('copy')) {
        document.execCommand('copy');
        console.log('复制成功');
      }
    })
  </script>
</html>

方法2 在div或者变量中的复制

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
    <button id="btn">点我复制</button>
  </body>
  <script>
    const btn = document.querySelector('#btn');
      btn.addEventListener('click',() => {
        const input = document.createElement('input');
        document.body.appendChild(input);
        input.setAttribute('value', '听说你想复制我');
        input.select();
        if (document.execCommand('copy')) {
          document.execCommand('copy');
          console.log('复制成功');
        }
        document.body.removeChild(input);
    })
  </script>
</html>

参考链接:

上一篇 下一篇

猜你喜欢

热点阅读