<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .cont{300px;height:400px;border:solid 1px black;margin:40px auto;} .msg{height: 300px;border-bottom:solid 1px black;box-sizing: border-box;overflow: auto;} .msg p{margin: 0;max- 220px;border-radius: 6px;margin: 6px;padding: 6px;clear: both;color: #fff;} .msg p:nth-child(2n){float: left;background: #277;} .msg p:nth-child(2n-1){float: right;background: #772;} .form{height: 100px;} .form *{border: none;background: none;padding: 0;margin: 0;float: left;height: 100px;} #txt{240px;resize: none;outline: none;padding: 10px;} #send{40px;border-left: solid 1px black;outline: none;} </style> </head> <body> <div class="cont"> <div class="msg"></div> <div class="form"> <textarea id="txt"></textarea> <input type="button" value="发送" id="send"> </div> </div> <script> var osend = document.getElementById("send") var otxt = document.getElementById("txt") var omsg = document.querySelector(".msg") osend.onclick = function(){ // 如果输入框为空,结束 if(otxt.value === "") return; // 创建元素 var p = document.createElement("p"); // 设置内容 p.innerHTML = otxt.value; // 插入元素 omsg.appendChild(p); // 清空输入框 otxt.value = ""; // 每次发送之后,设置滚动条的滚动距离为最大高度,保证绝对显示最下方信息 omsg.scrollTop = omsg.scrollHeight; }