<!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>
@import url('demo.css');
</style>
</head>
<body>
<form class="comment">
<label for="content">请留言:</label>
<textarea name="content" id="content" cols="30" rows="5" placeholder="不要超过100个字符" maxlength="100"></textarea>
<span class="notice">还可以输入100字</span>
<button class="submit" type="button" name="submit">提交</button>
</form>
<ul class="list"></ul>
<script>
//获取元素
//form
const comment = document.querySelector('.comment');
//textarea
const content = comment.content;
//btn
const submitBtn = comment.submit;
//ul
const commentList = document.querySelector('.list');
const notice = document.querySelector('.notice');
//提交按钮点击事件
submitBtn.onclick = (ev) => {
// console.log(content.value.trim().length);
let value = content.value.trim();
if (value.length > 0 && value.length<=100) {
//将留言插入到列表中
const newComment = document.createElement('li');
newComment.textContent = value;
newComment.style.boederBottom = '1px solid white';
newComment.style.minHeight = '3em';
//添加删除留言功能
//未每一条留言添加删除按钮
const deleteBtn = document.createElement('button');
deleteBtn.textContent = '删除';
deleteBtn.style.float = 'right';
deleteBtn.classList.add('del-btn')
deleteBtn.onclick = function(){
if (confirm('是否删除')){
//确定:true ,取消:false
this.parentNode.remove();
alert('删除成功')
content.focus();
return false;
}
}
//将删除按钮添加到新留言的后面
newComment.append(deleteBtn);
//将新留言添加到列表的头部
commentList.prepend(newComment);
//通知用户
alert('留言成功')
//清空留言
content.value = null;
content.focus();
//提示信息
notice.textContent = '还可以输入100字';
} else {
alert('没有内容或超过规定字数')
content.focus();
return false;
}
}
// oninput 监控输入, 提示信息
content.oninput=function(){
let textLength = content.value.trim().length;
notice.textContent = `还可以输入${100 - textLength}字`;
}
</script>
</body>
</html>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
li {
list-style: none;
}
body {
background-color:lightskyblue;
color: #555;
}
.comment {
width: 85%;
margin: 1em auto;
display: grid;
gap: 0.5em;
}
.comment #content {
resize: none;
border: none;
padding: 0.5em;
outline: none;
}
.comment #content:focus,
.comment #content:hover {
box-shadow: 0 0 8px steelblue;
transition: 0.6s;
}
.comment .submit {
width: 30%;
margin-left: auto;
background-color: lightseagreen;
border: none;
outline: none;
color: white;
height: 2.5em;
}
.comment .submit:hover {
background-color: seagreen;
transition: 0.6s;
cursor: pointer;
}
.list {
width: 80%;
/* background-color: yellow; */
margin: auto;
padding: 1em;
}
.del-btn {
background-color: wheat;
color: red;
padding: 0.5em 1em;
/* height: 2.2em; */
border: none;
outline: none;
}
.del-btn:hover {
cursor: pointer;
background-color: lime;
}