1.dom增删改
insertAdjacentElement 添加元素
insertAdjacentHTML与cloneNode 克隆节点
替换节点与删除节点
2.应用留言板
<!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>Document</title>
</head>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.ly{
width: 900px;
margin: 0 auto;
}
textarea{
width: 100%;
height: 112px;
resize: none;
border-radius: 10px;
padding-top: 10px;
padding-left: 20px;
outline: none;
font-size: 18px;
}
.bott{
display: flex;
justify-content: flex-end;
align-items: center;
}
button{
width: 100px;
height: 30px;
background-color: #0084ff;
border: none;
color: #fff;
font-family: 宋体;
font-size: 14px;
font-weight: bold;
transition: all 0.5s;
}
button:hover {
background: rgb(0, 225, 255);
}
p{
margin-right: 5px;
color: #666;
}
span{
color: #ff0000;
padding-right: 5px;
}
.info{
margin: 40px auto 0;
}
.xx{
width: 900px;
margin: 0 auto;
padding: 20px 0;
border-bottom: 1px dashed #ccc;
}
.xx .top{
display: flex;
justify-content: space-between;
}
.xx .left{
display: flex;
height: 84px;
}
.xx .left img{
height: 100%;
border-radius: 50%;
}
.xx .right{
margin-left: 20px;
align-self: center;
}
.xx .right h3{
font: bold 16px '宋体';
}
.xx .right p{
color: #aaa;
margin-top: 8px;
font-size: 12px;
}
.close span{
font-size: 28px;
}
.bottom{
padding-left: 100px;
color: #666;
word-break: break-all;
}
</style>
<body>
<div class="ly">
<div class="img">
<img src="./images/tip.png" alt="">
</div>
<textarea name="" id="" cols="30" rows="10" placeholder="说点什么吧..." maxlength="200"></textarea>
<div class="bott">
<p><span>0</span>/ 200</p>
<button>发布</button>
</div>
</div>
<div class="box1">
<div class="info">
</div>
</div>
</div>
<script>
let textarea=document.querySelector('textarea')
let span=document.querySelector('.bott span')
textarea.addEventListener('input',()=>span.innerHTML= textarea.value.trim().length)
let button=document.querySelector('.bott button')
button.addEventListener('click',()=>{
if(textarea.value.trim()===''){
textarea.value=''
span.innerText=0
alert('请输入内容')
textarea. focus()
return false
}
textarea.focus()
let xx=document.createElement('div')
xx.classList='xx'
xx.innerHTML=`
<div class="top">
<div class="left">
<div class="img"> <img src="https://img.php.cn/upload/avatar/000/991/210/62d10769ad48d159.jpg" alt=""></div>
<div class="right">
<h3>喜</h3>
<p>${new Date().toLocaleString()}</p>
</div>
</div>
<div class="close">
<span>
X
</span>
</div>
</div>
<div class="bottom">
<p>${textarea.value}</p>
</div>
`
document.querySelector('.info').insertAdjacentElement('afterBegin',xx)
textarea.value=null
span.innerHTML=0
let del=document.querySelector('.close span')
del.addEventListener('click',()=>document.querySelector('.info').removeChild(xx))
})
textarea.addEventListener('keyup',()=>{
if(event.key==='Enter')button.click()
})
</script>
</body>
</html>