Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
演示代码如下:
<!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>dom实战:留言板</title>
<style>
.user{
width: 500px;
height: 300px;
border: 1px solid lightblue;
position: relative;
top: 10px;
padding: 50px;
margin: auto;
}
.textBox{
width: 500px;
height: 250px;
border: 1px solid #CBA4C3;
margin: 0 auto;
}
h3{
text-align: center;
position: relative;
top: 10px;
}
p{
position: absolute;
left: 465px;
margin-top: 20px;
}
</style>
</head>
<body>
<!-- <input type="text" onkeydown="console.log(event.key)" placeholder="请输入内容" autofocus>
<ul class="list"></ul> -->
<h3>留言板</h3>
<div class="user">
<textarea class="textBox" onkeydown="addMsg(this)" placeholder="请输入内容" cols="30" rows="10" autofocus></textarea>
<ul class="list"></ul>
</div>
<p>感谢您的反馈!</p>
<script>
function addMsg(ele){
// console.log(event);
// console.log(event.key);
if (event.key==='Enter'){
// 1. 获取显示留言的容
const ul=document.querySelector('.list');
//2. 判断用户留言是否为空
if (ele.value.trim().length===0){
alert('用户留言不能为空');
ele.focus();
return false;
}
//3. 添加一条新留言
const li=document.createElement('li');
//console.log(ele.value);
// li.textContent=ele.value;
li.innerHTML=ele.value+'<button onclick="del(this.parentNode)">删除</button>';
ul.insertAdjacentElement('afterBegin',li);
//4. 将输入框中的前一条留言清空
ele.value=null;
//5. 焦点重置
ele.focus();
}
}
//删除
function del(ele){
// console.log(ele);
// ele.remove();
return confirm('是否删除?') ? ele.remove() : false;
}
</script>
</body>
</html>
效果如下图: