输入留言并在下方进行展示,可以删除当前评论,评论的字数不能超过100,如果超过则仍显示当前展示内容
<!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;
}
li {
list-style: none;
}
body {
background-color: rgb(174, 236, 236);
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;
}
.list li {
border-bottom: 1px solid #fff;
padding-bottom: 20px;
margin-bottom: 20px;
}
.del-btn {
background-color: wheat;
color: #000;
padding: 0.5em 1em;
/* height: 2.2em; */
border: none;
outline: none;
}
.del-btn:hover {
cursor: pointer;
background-color: rgb(31, 230, 163);
}
</style>
</head>
<body>
<form action="" class="comment" id="comment">
<label for="content">请留言</label>
<textarea name="content" id="content" cols="30" rows="10"></textarea>
<span class="notice">还可以输入100字</span>
<button class="submit" type="button" name="submit">提交</button>
</form>
<ul class="list"></ul>
</body>
</html>
js 部分
<script>
//获取元素
// form
let comment = document.forms.comment;
console.log(comment);
let content = comment.content;
let btn = comment.submit;
let commentList = document.querySelector(".list");
let notice = document.querySelector(".notice");
// 2给按钮添加事件
btn.onclick = (ev) => {
//获取留言内容
//console.log(content.value.trim().length);
// 长度不能超过100 而且大于0
if (content.value.trim().length > 0 && content.value.trim().length <= 100) {
// 创建留言内容标签然后插入到ul中
let li = document.createElement("li");
li.textContent = content.value;
// 添加删除按钮
let delbtn = document.createElement("div");
delbtn.textContent = "删除";
delbtn.style.float = "right";
delbtn.classList.add("del-btn");
delbtn.onclick = function () {
if (confirm('是否删除')) {
// li.remove();
this.parentNode.remove();
alert("留言删除成功");
}
}
li.append(delbtn);
commentList.prepend(li);
} else {
alert("长度超过100");
//超出之后并将输入内容清空
// content.value = '';
content.focus();
return false;
}
}
content.oninput = function () {
let textLength = content.value.trim().length;
notice.textContent = `还可以输入${100 - textLength}个字`;
let lastword = 100 - textLength;
if (lastword <= 0) {
alert("已输满100字");
content.value = content.value.trim().substring(0, 100);
// content.disabled = true;
// console.log(content.disabled);
notice.textContent = `还可以输入0个字`;
content.focus();
} else {
}
}
</script>