实现留言效果,超过5条留言 删除第一条
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.nav {
background-color: rgb(57, 67, 73);
height: 70px;
line-height: 70px;
}
.nav h2 {
color: #fff;
width: 100px;
height: 64px;
text-align: center;
background-color: rgb(59, 88, 70);
border: 3px solid rgb(229, 184, 17);
margin-left: 248px;
}
.publish {
border: 1px solid rgba(125, 125, 125, 0.5);
padding: 20px;
width: 1040px;
margin: 0 auto;
box-sizing: border-box;
}
#ipt {
border: 1px solid rgba(125, 125, 125, 0.5);
outline: none;
width: 978px;
height: 200px;
font-size: 16px;
padding: 10px;
}
.btn {
margin-top: 10px;
}
#btn {
border: none;
outline: none;
font-size: 18px;
width: 80px;
height: 40px;
color: #ffffff;
background-color: rgb(0, 148, 132);
}
#btn:hover {
opacity: 0.8;
}
#content {
width: 1040px;
height: 300px;
margin: 0 auto;
padding: 10px;
box-sizing: border-box;
}
#content p {
width: 600px;
font-size: 16px;
/* height: 60px; */
padding: 10px;
box-sizing: border-box;
margin-top: 10px;
/* position: absolute; */
}
</style>
</head>
<body>
<div class="nav">
<h2>留言墙</h2>
</div>
<div class="publish">
<div class="ipt">
<input type="text" name="" id="ipt">
</div>
<div class="btn">
<input type="button" value="发布" id="btn">
</div>
</div>
<div id="content">
<!-- <p>超过5条留言 删除第一条</p> -->
</div>
<script>
// 超过5条留言 删除第一条
let btn = document.getElementById('btn');
btn.addEventListener('click', btnClick);
//留言发布函数
function releaseMessage() {
let inpContent = document.getElementById('ipt').value;
let content = document.getElementById('content');
let message = document.createElement('p');
let d = new Date();
message.innerHTML = inpContent + '<br>' + d.toLocaleString();
// message.innerHTML = d.toLocaleString() + inpContent;
message.style.backgroundColor = getColor();
let messageNum = content.querySelectorAll('p');
// console.log(messageNum);
if (messageNum.length > 0) {
content.insertBefore(message, messageNum[0]);
} else {
content.appendChild(message);
}
}
//点击发布函数
function btnClick() {
let ipt = document.getElementById('ipt');
// console.log(ipt.value);
if (ipt.value === "") {
alert('请先输入留言!')
} else {
releaseMessage();
//判断留言长度,删除留言
let messageNum = document.querySelectorAll('p');
ipt.value = '';
// console.log(messageNum);
if (messageNum.length === 6) {
messageNum[5].remove();
}
}
}
//产生一个随机随机颜色
function getColor() {
var str = '0123456789abcdef'; // 0-15
var color = "#";
// 循环6次 每次随机生成一个字符
for (var i = 0; i < 6; i++) {
var num = rand(0, 15);
//color += str.charAt(num);
color += str[num];
}
return color;
}
//任意两个数之间的随机数
function rand(min, max) {
// Math.round(Math.random()*5+5) [5,10]
return Math.round(Math.random() * (max - min) + min);
}
</script>
</body>
</html>
效果图: