<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>QQ简易聊天窗口</title>
<link rel="stylesheet" href="../css/chat.css">
</head>
<body>
<section id="chat">
<div class="chatBody"></div>
<div><img src="../images/icon.jpg"></div>
<textarea class="chatText"></textarea>
<div class="btn"><span id="close">关闭(C)</span><span id="send">发送(S)</span></div>
</section>
</body>
<script src="../../adapter/jquery-3.4.1.js"></script>
<script>
let avatars = ["head01.jpg","head02.jpg","head03.jpg"];
let nicknames = ["追风少年","僵尸小鱼","古惑仔","美少女"];
let html = ``;
$("#send").on("click",function () {
sendContent();
})
//关闭当前窗口
$("#close").on("click",function () {
self.close();
});
//聊天的内容
function sendContent() {
let content=$(".chatText").val();
if (content==""){
alert("输入不能为空");
$(".chatText").focus();
}
else{
let index=Math.floor(Math.random()*avatars.length);
let avatar=avatars[index];
let nickname=nicknames[index];
//模板字符串拼接
html
+=`
<section>
<div><img src="../images/${avatar}" alt="用户头像" width="30" height="30"></div>
<p>${nickname}</p>
<div class="chatContent">${content}</div>
</section>
`;
//将内容放入chatText中
$(".chatBody").html(html);
//垂直滚动条始终出现底部
//scrollTop相对滚动条顶部的偏移 srcollHeight 相对滚动条的高度
//".chatBody")[0] 表示class= chatBody 元素和中国的第一个子元素
$(".chatBody")[0].scrollTop = $(".chatBody")[0].scrollHeight;
//清空输入框内容
$(".chatText").val("");
}
}
$(document).on("keydown",function (event) {
if(event.which == 13|| (event.ctrlKey && event.which == 13)){
sendContent();
}
});
</script>
</html>
转载于:https://www.cnblogs.com/taoist123/p/11160178.html