前段时间学习了JavaScript,学的网课视频老师利用js做了简易的留言板
最近趁空闲时间自己也敲了一边
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
li {
list-style-type: none;
display: flex;
flex-wrap: wrap;
margin: 5px 0px;
}
button {
width: 25px;
height: 20px;
margin: 5px 0px;
}
ul {
width: 190px;
margin: 10px;
}
span {
display: inline-block;
width: 165px;
height: 20px;
line-height: 20px;
}
.rm {
display: none;
width: 130px;
margin: 10px;
}
.text1 {
margin: 5px;
}
</style>
</head>
<body>
<input type="text" class="text1">
<button class="btn">Add</button>
<ul>
</ul>
<button class="rm"></button>
<script>
function empty(e) {
while (e.firstChild) {
e.removeChild(e.firstChild);
}
}
var count = 0;
let btn = document.querySelector('.btn');
let text = document.querySelector('input');
let ul = document.querySelector('ul');
let rm = document.querySelector('.rm');
btn.onclick = function () {
if (text.value == 0) {
return false;
}
else {
var li = document.createElement('li');
var button = document.createElement('button');
var span = document.createElement('span');
button.className = "del";
button.innerHTML = 'x';
span.innerHTML = text.value;
ul.appendChild(li);
li.appendChild(span);
li.appendChild(button);
text.value = ""
count++;
}
if (count > 0) {
rm.innerHTML = "remove all " + count + " items";
rm.style.display = "block"
}
var delect = document.querySelectorAll(".del");
console.log(delect);
for (let i = 0; i < delect.length; i++) {
delect[i].onclick = function () {
ul.removeChild(this.parentNode);
count--;
if (count < 1) {
rm.style.display = "none";
}
rm.innerHTML = "remove all " + count + " items";
}
}
console.log(count);
};
rm.onclick = function () {
count = 0;
empty(ul);
rm.style.display = "none";
}
</script>
</body>
</html>
效果如下