js 留言板
<style>
* {
padding: 0;
margin: 0;
}
.wrap {
width: 800px;
border: 1px solid black;
padding: 20px;
margin: 0 auto;}
.wrap h3 {
margin: 10px 0 20px;
}
.message {
padding: 10px;
border: 1px dashed #ccc;}
.info {
display: flex;
justify-content: space-between;
border-bottom: 1px dashed #ccc;
padding-bottom: 10px;
margin-bottom: 10px;}
.content {
width: calc(100% - 2px);
height: 120px;
border-radius: 5px;
border-color: #ccc;
vertical-align: middle;
margin: 10px 0; }
.btn {
text-align: right;
}
</style>
<body>
<div class="wrap">
<h3>留言板</h3>
<!-- dvsdv -->
<div class="exhibit" id="exhibit">
<div class="message">
<div class="info">
<span>张三</span>
<span>2019-12-12</span>
</div>
<p>今天天气不错</p>
<div class="btn">
<a href="#" class="removeBtn" _id="0">删除</a>
</div>
</div>
</div>
<div class="messageText">
<textarea class="content" id="content"></textarea>
<div class="btn">
<input type="button" value="留言" id="addBtn">
</div>
</div>
</div>
<script>
let data = [{
username: "张三0",
time: "2017-09-07 09:11:00",
text: "留言内容0"}, {
username: "张三1",
time: "2017-09-08 09:11:00",
text: "留言内容0"}, {
username: "张三2",
time: "2017-09-09 09:11:00",
text: "留言内容0"}];
render(); //调用渲染函数
addBtn.addEventListener("click", () => { // addEventListener 添加事件监听,类似于 on 来触发
addMessage();
})
content.addEventListener("keydown", (e) => { // 键盘enter事件
if (e.keyCode === 13) {
addMessage();
}
}, false)
// 删除的用法
exhibit.addEventListener("click", (e) => {
console.log(e)
if (e.target.className === "removeBtn") {
e.preventDefault(); // 阻止默认事件
let i = e.target.getAttribute("_id"); // 获取上面的ID,渲染时候存上去的索引值
data.splice(i, 1); // 根据索引值,把数组里面的数据删除
render(); // 然后重新调用渲染函数,设置html内容
}
}, false)
// 增加新的留言数据 把数据拼接好,放进数组,然后调用渲染函数,渲染函数每次都是取数组里面的值
function addMessage() {
data.push({
username: `张三${data.length}`,
time: getNowTime(),
text: content.value
});
content.value = ""; // 清空输入框里面的值
render();
}
// 数据渲染到页面上
function render() {
let newArr=data.map((item, index) => { // map 用来遍历数组,然后循环拼接起来字符串 _id是自己加的属性,存放索引值
console.log(item,index)
return `<div class="message">
<div class="info">
<span>${item.username}</span>
<span>${item.time}</span>
</div>
<p>${item.text}</p>
<div class="btn">
<a href="#" class="removeBtn" _id="${index}">删除</a>
</div>
</div>`
})
console.log(newArr)
let str =newArr.join("");
console.log(str)
exhibit.innerHTML=str;
}
// 获取当前时间 格式:XXXX-XX-XX XX:XX:XX
function getNowTime() {
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth() + 1;
month = judgeTime(month);
let day = date.getDate();
day = judgeTime(day);
let hours = date.getHours();
hours = judgeTime(hours);
let minutes = date.getMinutes();
minutes = judgeTime(minutes);
let seconds = date.getSeconds();
seconds = judgeTime(seconds);
let nowTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
return nowTime;
}
// 在一位数的时间前加 0
function judgeTime(time) {
if (time < 10 && time > 0) {
time = "0" + time;
}
return time;
}
</script>
</body>
效果图:
浙公网安备 33010602011771号