<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<title>socket.io</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
body{
padding: 10px;
}
.chat-box{
border: 1px solid #aaa;
width: 300px;
height: 600px;
border-radius: 6px;
overflow-y: auto;
position: relative;
}
ul,li{
list-style: none;
}
ul{
padding: 10px;
}
li{
line-height: 30px;
margin-bottom: 10px;
}
li span{
display: inline-block;
width: 30px;
height: 30px;
background-color: #ccc;
border-radius: 50%;
margin-right: 5px;
}
li div{
border: 1px solid #ccc;
width: 80%;
border-radius: 6px;
padding: 5px;
word-break: break-all;
word-wrap: break-word;
white-space: pre-wrap;
}
.sendBox{
width: 300px;
height: 38px;
position: relative;
top: -10px;
background-color: cornflowerblue;
border: 1px solid #aaa;
border-top: none;
border-radius: 0 0 6px 6px;
overflow: hidden;
}
.sendBox input {
height: 25px;
width: 230px;
margin-top: 4px;
margin-left: 10px;
}
.sendBox button{
height: 29px;
width: 42px;
}
.chat-box::-webkit-scrollbar {/*滚动条整体样式*/
width: 4px; /*高宽分别对应横竖滚动条的尺寸*/
height: 1px;
}
.chat-box::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
border-radius: 10px;
-webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
background: #ccc;
}
</style>
</head>
<body>
<div class="chat-box">
<ul></ul>
</div>
<div class="sendBox">
<input type="text" name="sendMsg" id="sendMsg" value="" onkeypress="sendMsg()" />
<button id="sendBtn">发送</button>
</div>
<script type="text/javascript">
var socket = io.connect('http://localhost:8888');
socket.on('connected', function (data) {
console.log(data.hello);
$("ul").append('<li><span style="float: left;"></span><div style="margin-left: 35px;">'+data.hello+'</div></li>')
});
$("#sendBtn").click(function(){
sendFun()
})
function sendMsg() {
if(event.keyCode==13){
sendFun()
}
}
function sendFun() {
if ($("#sendMsg").val() != '') {
$("ul").append('<li><span style="float: right;"></span><div>'+$("#sendMsg").val()+'</div></li>')
socket.emit('sendNews', { id: 'demo',sendId: 'index', msg: $("#sendMsg").val() })
$("#sendMsg").val('')
$('.chat-box').scrollTop($('ul').height())
}
}
socket.on('news-demo', function (data) {
$("ul").append('<li><span style="float: left;"></span><div style="margin-left: 35px;">'+data.msg+'</div></li>')
$('.chat-box').scrollTop($('ul').height())
})
</script>
</body>
</html>