原生javasript实现Ctr+c复制Ctr+v粘贴

这里写图片描述

<!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>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值