1. 留言板添加字数与限制字符
写留言板
<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;
}
.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;
}
</style>获取元素
<script>const comment = document.querySelector('.comment');
const content = comment.content;
const submitBtn = comment.submit;
const commentList = document.querySelector('.list');
添加字数,限制字符,新留言前置
submitBtn.onclick = (ev) => {
let value = content.value.trim();
if (value.length > 0 && value.length <= 100) {
const newComment = document.createElement("li");
newComment.textContent = value;
newComment.style.borderBottom = "1px solid white";
newComment.style.minHeight = "3em";
新留言前置,留言成功
commentList.prepend(newComment);
alert("left message successful");
清空留言,无内容或超字数
content.value = null;content.focus();
} else {
alert("no content or too many words");
content.focus();
return false;
}
};
添加删除留言button
newComment.append(deleteBtn);
const deleteBtn = document.createElement(“button”);
deleteBtn.textContent = “delete”;
deleteBtn.style.float = “right”;
deleteBtn.classList.add(“del-btn”);确定是否删除
deleteBtn.onclick = function () {
if (confirm(“are you sure delete”)) {this.parentNode.remove();
alert("delete successful");
content.focus();
return false;
}
};
2. 字符串和数组
- concat()拼装
- slice(start, end)取子串
- substr(start, size): 取子串
- trim(): 删除字符串二边的空白字符
- 将字符串打散成数组