效果图
代码
<!DOCTYPE html>
<html lang="zh-CN">
<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>留言板实战</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
/* border: 1px solid red; */
}
li {
list-style: none;
}
.ground {
display: grid;
grid-template-columns: repeat(2, 1fr);
place-items: center;
}
.ban {
background-color: aqua;
width: 490px;
height: 500px;
display: grid;
grid-template-rows: repeat(2, 2fr);
place-items: center;
}
.windows {
background-color: aquamarine;
width: 490px;
height: 500px;
}
ul {
position: relative;
}
input {
padding: 60px;
height: 100px;
width: 400px;
border-radius: 5px;
outline: none;
}
button {
width: 20px;
height: 20px;
font-size: 15px;
line-height: 15px;
text-align: center;
border-radius: 50%;
background-color: mediumvioletred;
position: absolute;
right: 0;
}
</style>
</head>
<body>
<div class="ground">
<div class="ban">
<input
type="text"
placeholder="请输入留言"
ds
onkeydown="addMsg(this)"
autofocus
/>
<hr style="width: 100%" />
<div class="zhanshi">
<ul class="list" style="width: 485px; height: 365px"></ul>
</div>
</div>
<div class="windows"></div>
</div>
<script>
function addMsg(ele) {
if (event.key === "Enter") {
let ul = document.querySelector(".list"); //获取ul元素
if (ele.value.trim().length === 0) {
//判断内容是否为空。trim方法可以去除字符串中的空格
alert("不能为空");
ele.focus();
return false;
}
const li = document.createElement("li");
li.innerHTML =
ele.value +
`<button onclick = "del(this.parentNode)">x</button><hr>`; //添加一个删除按钮
ul.insertAdjacentElement("afterBegin", li); //在上条留言上部插入一条留言
ele.value = null; //清空输入框
ele.focus(); //重置焦点
}
}
function del(ele) {
return confirm("是否删除本条留言?") ? ele.remove() : false;//判断是继续执行清除本元素的命令
}
</script>
</body>
</html>