利用 jQuery 做一个备忘录,有记录,选中删除,选中拷贝等功能:
html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>节点操作练习</title>
<link rel="stylesheet" href="./css/style.css">
</head>
<body>
<div id="box">
<div id="box1">
<div class="centerWarp">
<input type="text" id="inp" placeholder="请输入内容">
</div>
<button id="inc">增加</button>
<button id="remove">删除</button>
<button id="copy">拷贝</button>
</div>
<div id="box2"></div>
</div>
<script src="./src/jquery-3.3.1.js"></script>
<script src="./src/sw.js"></script>
</body>
</html>
css 文件
#box {
width: 200px;
height: 400px;
margin: 100px auto;
outline: black solid 1px;
background-color: rgb(95, 166, 179);
}
#box1 {
width: 200px;
height: 80px;
background-color: rgb(63, 131, 177);
}
button {
margin: 10px;
}
.centerWarp {
text-align: center;
}
#inp {
margin-top: 5px;
width: 180px;
height: 30px;
}
js 文件
// 随机颜色
function randomColor() {
let str = `rgb(${parseInt(Math.random()*256)},
${parseInt(Math.random()*256)},
${parseInt(Math.random()*256)})`;
return str;
}
selectID = -1; // 用于记录选择容器下标,-1代表无,0及以上代表选中
// 增加按钮点击效果
$('#inc').click(function () {
if (!$('#inp').val()) {
alert('输入内容不能为空');
} else {
let newDiv = document.createElement('div'); // 创建新容器
newDiv.innerHTML = $('#inp').val(); // 新容器内的文字等于输入框内的值
newDiv.style.backgroundColor = randomColor(); // 设置容器背景颜色
$('#box2').append(newDiv); // 将新容器添加到 box2 中
newDiv.onclick = function() { // 选择后记录及效果
if(selectID !== -1) {
$('#box2').children()[selectID].style.outline = 'none';
}
const id = getID(this);
selectID = id;
this.style.outline = '2px solid red';
}
}
})
// 获得 box2 中所点击容器的下标
function getID(div) {
const child = $('#box2').children();
for(let i = 0; i < child.length; i++) {
if(div === child[i]) {
return i;
}
}
}
// 删除按钮
$('#remove').click(function () {
if(selectID === -1) {
alert('没有选择!');
return;
}
$('#box2').children()[selectID].remove();
selectID = -1;
})
// 拷贝按钮
$('#copy').click(function () {
if(selectID === -1) {
alert('没有选择!');
return;
}
const newNode = $('#box2').children()[selectID].cloneNode(true);
newNode.style.outline = 'none';
$('#box2').append(newNode);
})
效果如下: