#box2{
width: 400px;
height: 500px;
border: solid 1px black;
margin: 20px auto;
}
.msg{
height: 400px;
border-bottom: solid 1px black;
overflow: auto;
}
.msg div{
max-width: 300px;
padding: 4px;
margin: 4px;
border-radius: 4px;
clear: both;
}
.msg div:nth-child(2n){
float: left;
background: #55f;
}
.msg div:nth-child(2n-1){
float: right;
background: #5f5;
}
.form{height: 99px;}
.form *{margin: 0;padding: 0;border: 0;float: left;}
#txt1{
width: 300px;
height: 99px;
border-right: solid 1px black;
}
#btn1{
width: 99px;
height: 99px;
display: block;
}
HTML代码
<div id="box2">
<div class="msg"></div>
<div class="form">
<input type="text" id="txt1">
<input type="button" id="btn1" value="发送">
</div>
</div>
JavaScript代码
var txt1 = document.getElementById("txt1");
var btn1 = document.getElementById("btn1");
var msg = document.querySelector(".msg")
btn1.onclick = function(){
if(txt1.value == ""){
return;
}
var div = document.createElement("div");
div.innerHTML = txt1.value;
msg.appendChild(div);
txt1.value = "";
msg.scrollTop = msg.scrollHeight;
}