<!DOCTYPE html>
<html lang="zh-CN">
<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>简单的留言板功能</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);
height: 98.5vh;
}
.container {
margin: 0 auto;
padding: 0 20px;
max-width: 1170px;
}
h1 {
margin: 15px 0;
}
textarea {
display: block;
width: 100%;
height: auto;
min-height: 300px;
line-height: 20px;
margin-bottom: 20px;
padding: 5px 10px;
border: 1px solid transparent;
border-radius: 2px;
transition: all .3s;
outline: 0;
resize: vertical;
}
textarea:focus {
border-color: #03a9f4 !important;
}
button {
min-width: 100px;
height: 38px;
line-height: 38px;
border: 1px solid #eaeaea;
color: #666;
padding: 0 18px;
background-color: #fff;
text-align: center;
font-size: 14px;
border-radius: 2px;
cursor: pointer;
transition: all .3s;
}
button:hover {
opacity: .8;
border-color: #03a9f4;
}
.list>li {
display: flex;
place-content: space-between;
background-color: #fff;
line-height: 36px;
margin-bottom: 5px;
border-radius: 5px;
padding: 0 8px;
}
</style>
</head>
<body>
<div class="container">
<h1 style="text-align: center;">留言板</h1>
<div class="message" style="margin-bottom: 20px;">
<textarea placeholder="请输入留言内容, 也可以使用快捷键Ctrl+Enter提交"></textarea>
<div style="text-align: right;">
<button>提交</button>
</div>
</div>
<ul class="list">
</ul>
</div>
<script>
let text = document.querySelector("textarea");
let btn = document.querySelector("button");
let list = document.querySelector(".list");
// 监听提交快捷键: Ctrl+Enter
text.addEventListener('keypress', function (event) {
if (event.key == "\n") {
btn.click();
}
})
// 监听点击提交按钮
btn.addEventListener('click', function (event) {
submit();
})
function submit() {
if (text.value.length === 0) {
alert('留言不能为空');
text.focus();
return false;
}
let itemsView = `
<li>
<div>${text.value}</div>
<div>${getDate()}</div>
</li>
`;
list.insertAdjacentHTML("afterbegin", itemsView);
text.value = '';
alert('提交成功');
}
function getDate() {
let date = new Date();
return date.getFullYear() + '-' + date.getMonth() + '-' + date.getDay() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
}
</script>
</body>
</html>