效果图:
HTML代码
<div class="wrapper">
<div class="active">
<span>欢迎来到吐槽大厅</span>
</div>
<div class="add">
<h3>用户名</h3>
<input type="text" placeholder="用户名" class="user">
<h3>吐槽内容</h3>
<textarea class="pwd" cols="10" rows="10"></textarea><br>
<!-- <input type="text" placeholder="吐槽内容" class="pwd"><br> -->
<button class="btn">提交</button>
</div>
<div class="search">
<h1>吐槽回复:</h1>
<ul>
<!-- <li><span>tom</span>说<span>妈妈,我想吃烤山药</span><a href="#" class="tb">删除</a></li> -->
</ul>
</div>
</div>
css样式
<style>
*{
list-style: none;
}
.wrapper{
margin: 0 auto;
width: 800px;
height: 600px;
border: 1px solid black;
}
.active{
width: 100%;
height: 100px;
background-color: gray;
text-align: center;
}
.active span{
line-height: 100px;
font-size: 50px;
}
.add{
display: inline-block;
margin-left: 30px;
margin-top: 40px;
}
.add button{
margin-top: 50px;
width: 70px;
height: 40px;
}
.search{
float: right;
width: 500px;
}
.search ul {
overflow-y: auto;
height: 400px;
overflow-x: hidden;
}
.search ul li{
height: 50px;
width: 390px;
border: 1px solid gray;
margin-right: 30px;
line-height: 50px;
padding: 10px;
position: relative;
}
.search ul li span:nth-of-type(1){
display: none;
}
.search ul li button{
display: inline-block;
color: gray;
text-decoration: none;
margin-left: 200px;
position: absolute;
top: 10px;
right: 10px;
}
</style>
JavaScript代码
<script src="./jquery-3.6.0.js"></script>
<script>
$(function(){
//唯一标识id
var nextId=localStorage.nextId==undefined?0:localStorage.nextId*1;
//获取数组
var userArr=localStorage.userArr==undefined?[]:JSON.parse(localStorage.userArr);
//添加
$(".btn").click(function(){
//获取 吐槽姓名内容
var username=$(".user").val();
var nei=$(".pwd").val();
// 封装对象
var obj={
id:nextId++,
user:username,
pwd:nei
}
console.log(obj);
//2、向数组添加最新的数据
userArr.push(obj);
//3、本地存储更新
localStorage.userArr=JSON.stringify(userArr);
//4、渲染页面
//5、清空textarea
$(".user").val("");
$(".pwd").val("");
show();
})
// 渲染页面
show(); //第一次进入页面调用
function show(){
$("ul").html("");
userArr=localStorage.userArr==undefined?[]:JSON.parse(localStorage.userArr);
userArr.forEach(obj=>{
$("ul").append(`<li>
<span>${obj.id}</span>
<b>${obj.user}</b><span>说</span>:<b>${obj.pwd}</b>
<button class="tb">删除</button>
</li>`)
})
}
$("ul").on("click", ".tb", function() {
if (confirm("确认删除吗?")) {
userArr=localStorage.userArr==undefined?[]:JSON.parse(localStorage.userArr);
//获取对应标题
var id = $(this).parent().children().eq(0).html();
console.log(id);
var index=userArr.findIndex(obj=>{
return obj.id==id;
})
console.log(index);
userArr.splice(index, 1);
localStorage.userArr = JSON.stringify(userArr);
show();
}
})
})
</script>
需要引用下载jQuery