您的位置:首页 > Web前端 > JavaScript

用原生JS模拟一个聊天记录表

2016-11-01 18:57 127 查看
这是一个模拟聊天记录的案例,初学者可以通过本例对来加深JS的事件的熟悉和理解。

话不多说,我们先来看一下效果图吧。



下面开始说明怎么写吧。

HTML结构:

<div id="main" class="main">
<ul id="content" class="content">
<li class="msgContent left">你好</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 中添加一条消息记录 -->

</ul>
<textarea id="msg_input" class="msgInput"></textarea>
<button id="sendbtn" class="sendbtn">发送</button>


先看看JS代码吧:

//获取节点
var oInput = document.getElementById("msg_input");
var oBtn = document.getElementById("sendbtn");
var oContent = document.getElementById("content");//ul

//点击发送
oBtn.onclick = function()
{
//内容输出
var str = oInput.value;//获取输入框的值
var oLi = document.createElement("li");//创建li标签
oLi.innerHTML = str;//节点内容
oContent.appendChild(oLi);//把新建的li标签压入ul中

//对li添加发送消息的样式
oLi.className = "msgContent right";

//清除li的浮动:
oLi.style.clear = "both";

//设置发送内容后输入框的数据清空:
oInput.value = "";

//保持当前节点对象在最可见区域
oLi.scrollIntoView();
}

//按下Ctrl+Enter回车键完成发送
oInput.onkeydown = function(e)
{
e = e || window.event;
if (e.ctrlKey && e.keyCode == 13)
{
oBtn.onclick();//执行发送内容
}
}


CSS样式(重点在JS,这只是一些美观样式):

*{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;
}


这只是一个很简单的例子。

下一篇博客会写如何在局域网内进行聊天。

(觉得好就【顶】一个)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: