运行结果截图
CSS样式
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
li {
list-style: none;
}
.comment-send {
margin: 100px auto;
width: 1200px;
}
.user-face {
position: absolute;
width: 65px;
height: 65px;
}
.user-face img {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100%;
height: 100%;
vertical-align: middle;
border-radius: 50%;
}
.textarea-container {
position: relative;
width: 638px;
height: 65px;
margin-bottom: 10px;
}
.textarea-container textarea {
position: relative;
display: inline-block;
margin-left: 75px;
outline: none;
resize: none;
font-family: sans-serif;
font-size: 12px;
color: #555;
padding: 5px 10px;
width: 470px;
height: 65px;
background-color: #f4f5f7;
border: 1px solid #e5e9ef;
cursor: text;
text-indent: 2px;
}
.textarea-container button {
display: inline-block;
width: 70px;
height: 65px;
position: absolute;
right: 15px;
top: 0px;
padding: 4px 15px;
font-size: 14px;
color: #fff;
border-radius: 4px;
text-align: center;
vertical-align: top;
cursor: pointer;
background-color: #00a1d6;
border: 1px solid #00a1d6;
transition: 0.1s;
}
.comment-list ul {
margin-left: 75px;
}
.comment-list li {
border: 1px solid #ccc;
width: 300px;
padding: 5px;
background-color: #f4f5f7;
padding: 2px 0;
font-size: 14px;
text-shadow: none;
padding: 5px;
margin-bottom: 5px;
}
.comment-list li a {
float: right;
}
</style>
HTML结构
<body>
<div class="comment-send">
<div class="user-face">
<img src="images/ldh.jpg" alt="">
</div>
<div class="textarea-container">
<textarea cols="80" rows="5" placeholder="发一条友善的评论" name="" id=""></textarea>
<button>发布评论</button>
</div>
<div class="comment-list">
<ul>
</ul>
</div>
</div>
</body>
JavaScript代码
<script>
var textarea_container = document.querySelector('.textarea-container');
var textarea = textarea_container.querySelector('textarea');
var btn = textarea_container.querySelector('button');
var comment_list = document.querySelector('.comment-list');
var ul = comment_list.querySelector('ul');
btn.onclick = function () {
if (textarea.value == '') {
alert('请输入内容');
}
else {
//(1) 生成元素
var li = document.createElement('li');
//(2) 添加元素和删除链接 javascript:;防止链接跳转
li.innerHTML = textarea.value + "<a href = 'javascript:;'>删除</a>";
// ul.appendChild(li); 最新评论在下面
ul.insertBefore(li, ul.children[0]); //最新评论在最上面
//(3) 删除元素
li.children[0].onclick = function () {
ul.removeChild(this.parentNode);
}
}
}
</script>