原生javasript實現Ctr+c複製Ctr+v貼上

codingNoob發表於2018-09-04

這裡寫圖片描述

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>javasript實現Ctr+c複製Ctr+v貼上</title>
  <style>
    .copy .box{
      display: inline-block;
      background:#c25454;
      height:100px;
      width:100px;
      line-height:100px;
      color:#fff;
    }
    .copy .box.active{
      background:red;
    }
    .content{
      float:left;
      margin:10px 0;
      height:800px;
      width:800px;
      background:#ccc;
    }
    .content .paste-box .box{
      display: inline-block;
      background:#c25454;
      height:100px;
      width:100px;
      margin:10px;
      line-height:100px;
      color:#fff;
    }
  </style>
</head>
<body>
  <div class="copy">
    <div class="box">複製的內容1</div>
    <div class="box">複製的內容2</div>
    <div class="box">複製的內容3</div>
    <div class="box">複製的內容4</div>
  </div>
  <div class="content">
    <h4>貼上的內容區域</h4>
    <div class="paste-box"></div>
  </div>
</body>
<script>
  let pasteBox = document.querySelector('.paste-box');
  // 點選選中的元素集合
  let arrDom = [];
  // 點選的要複製的元素
  let copyElm = Array.prototype.slice.call(document.querySelectorAll('.copy .box'), 0);
  copyElm.forEach((item, index) => {
    item.addEventListener('click', () => {
      arrDom = [];
      item.classList.toggle('active');
      // 將所有選中要複製的元素新增儲存容器裡面
      arrDom = Array.prototype.slice.call(document.querySelectorAll('.copy .box.active'), 0);
    }, false);
  });

  document.onkeyup = function (event) {
    // 複製
    if (event.ctrlKey == 1) {
      if (event.key === 'c') {
        console.log(arrDom);
        console.log('複製成功!');
      }
    }
    // 貼上
    if (event.ctrlKey == 1) {
      if (event.key === 'v') {
        console.log('ctr+v');
        arrDom.forEach((item, index) => {
          pasteBox.appendChild(item.cloneNode(true));
        });
      }
    }
  };
</script>
</html>

相關文章