【JavaScript练习】创建留言板发布留言
运行结果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.msg {
width: 300px;
height: 200px;
margin: 100px auto;
position: relative;
}
button {
position: absolute;
top: 20%;
right: 10px;
}
textarea {
resize: none;
outline: none;
width: 250px;
height: 100px;
}
li {
background-color: pink;
color: #e61515e7;
font-size: 16px;
margin-bottom: 5px;
padding-left: 10px;
}
</style>
</head>
<body>
<!-- 发布留言案例 -->
<div class="msg">
<textarea name="" id="" cols="" rows="" placeholder="input msg..."></textarea>
<button>发布</button>
<ul>
</ul>
</div>
<script>
var text = document.querySelector('textarea');
var btn = document.querySelector('button');
var ul = document.querySelector('ul');
btn.onclick = function() {
// 判断内容是否为空
if (text.value == '') {
alert('不能输入空的留言内容');
} else {
// 创建新留言
var li = document.createElement('li');
li.innerHTML = text.value;
// 添加新留言
// ul.appendChild(li);
ul.insertBefore(li, ul.children[0]);
}
}
</script>
</body>
</html>