JQuery 实现简单的聊天对话框
程序员文章站
2022-07-13 23:24:54
...
聊天对话框
效果图:
基本代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>聊天对话框</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
*{font-size: 14px; padding:0; margin:0;}
.main{
position: relative;
margin: 20px auto;
border: 1px solid steelblue;
width: 430px;
height: 400px;
}
.msgInput{
display: block;
width: 406px;
height: 60px;
margin: 10px auto;
}
.sendbtn{
position: absolute;
width: 100px;
height: 29px;
bottom: 5px;
right: 10px;
}
.content{
list-style: none;
width: 410px;
height: 280px;
margin: 5px auto;
border: 1px dotted #D1D3D6;
overflow-y: scroll;
}
.msgContent{
width:auto;
max-width: 250px;
height: auto;
word-break: break-all;
margin: 5px;
padding: 3px;
border-radius: 5px;
}
.content .left{
float: left;
text-align: left;
background-color: lightgrey;
}
.content .right{
float: right;
text-align: right;
background-color: yellowgreen;
}
</style>
</head>
<body>
<div id="main" class="main">
<ul id="content" class="content">
<li class="msgContent left">你在干啥?</li>
<div style="clear:both"></div>
<li class="msgContent right">在和你聊天</li>
<div style="clear:both"></div>
<li class="msgContent left">哦</li>
<div style="clear:both"></div>
<li class="msgContent right">嗯</li>
<div style="clear:both"></div>
<li class="msgContent left">是不是可无聊</li>
<div style="clear:both"></div>
<li class="msgContent right">你也知道啊</li>
<div style="clear:both"></div>
</ul>
<textarea id="msg_input" class="msgInput"></textarea>
<button id="sendbtn" class="sendbtn">发送</button>
<script type="text/javascript">
$(function(){
$('.sendbtn').click(function(){
var content = $('#msg_input').val();
$('#content').append('<li class="msgContent right">'+content+'<li>').append
('<div style="clear:both"></div>');
$('#msg_input').val('')
});
$(window).keydown(function(e){
if(e.ctrlKey && e.keyCode==13){
var content = $('#msg_input').val();
$('#content').append('<li class="msgContent right">'+content
+'<li>').append('<div style="clear:both"></div>');
$('#msg_input').val('')
}
})
})
</script>
</body>
</html>