<!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>