留言板
效果图
代码
<!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>留言板</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body .lyb .srk input {
padding: 30px;
height: 50px;
width: 200px;
border-radius: 5px;
outline: none;
}
.lyb {
width: 50%;
height: 100%;
background-color: cadetblue;
}
.srk {
display: grid;
place-content: center;
height: 100px;
}
ul {
position: relative;
}
li {
list-style: none;
}
button {
font-size: 15px;
line-height: 15px;
text-align: center;
border-radius: 50%;
background-color: mediumvioletred;
position: absolute;
right: 0;
}
</style>
</head>
<body>
<div class="lyb">
<div class="srk">
<input
type="text"
onkeydown="addMsg(this)"
placeholder="请输入类容"
autofocus
/>
</div>
<ul class="list"></ul>
</div>
<script>
function addMsg(ele) {
if (event.key === 'Enter') {
// 获取留言板类容
const ul = document.querySelector('.list');
//判断用户留言是否为空
if (ele.value.trim().length === 0) {
alert('留言不能为空');
ele.focus();
return false;
}
//添加一条留言
const li = document.createElement('li');
li.innerHTML =
ele.value + '<button onclick="del(this.parentNode)">删除</button>';
ul.insertAdjacentElement('afterBegin', li);
//将输入框中的前一条留言清空
ele.value = null;
//焦点重置
ele.focus();
}
}
//删除
function del(ele) {
return confirm('是否删除' ? ele.remove() : false);
}
</script>
</body>
</html>