<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
ul {
list-style: none;
padding: 0;
margin: 0;
}
.msg-list {
position: relative;
width: 600px;
margin: 0 auto;
}
.msg-list ul {
padding: 10px;
min-height: 200px;
max-height: 400px;
/*超出部分出現滾動條*/
overflow-y: auto;
border: 1px solid #ddd;
}
.msg-list li {
float: left;
clear: both;
margin: 10px 0;
padding: 5px;
line-height: 2;
border-radius: 5px;
background-color: #efefef;
}
.msg-list li.active {
float: right;
background-color: #58bc58;
color: #fff;
}
.msg-list textarea {
display: block;
min-height: 50px;
margin: 10px 0;
width: 100%;
box-sizing: border-box;
}
.status {
display: none;
position: absolute;
left: 0;
bottom: 0;
right: 0;
padding: 5px 10px;
text-align: center;
color: #999;
}
</style>
<script>
window.onload = function () {
var auto = document.getElementById("auto");//經過id獲取元素的集合
var dialog = auto.children[0];//獲取第一個元素ul
var texInput = auto.children[1];//獲取第二個元素textarea
var but = auto.children[2];//獲取第三個元素按鈕
var status = auto.children[3];//獲取第四個元素div
var arrq = ["你好", "你叫什麼", "你幾歲了", "你姓什麼", "你來自哪裏"];//提問數組
var arra = ["你好哇", "我是元氣滿滿的萌妹子", "你問這個幹什麼", "尼古拉·阿列克謝耶維奇·奧斯特洛夫斯基", "我在你的心裏深處"];//回答數組
function creat() {//封裝函數 點擊和回車都會用到。
var val = texInput.value.trim();//獲取輸入文本域的值
if (val) {//判斷是否爲空
//非空
var li = document.createElement("li");//建立節點
li.innerHTML = val;//設置內容到節點
li.className = "active";//設置類名 應用相應的樣式
dialog.appendChild(li);//插入節點
dialog.scrollTop = dialog.scrollHeight - dialog.offsetHeight - 2;//計算可視窗口須要滾動的距離。
texInput.value = "";//清空內容
texInput.focus();//聚焦
status.style.display = "block";//顯示div
var atex = "";//建立一個字符串 接收回答
var index = arrq.indexOf(val);//獲取提問的問題在提問中數組的索引值
if (index >= 0) {//判斷提問的問題是否存在
//存在
atex = arra[index];//在回答數組中找到對應的索引值的數據並賦值給接收的字符串。
}
else {//不存在
atex = "What are you talking about?";
}
var ali = document.createElement("li");//建立節點 回答節點
ali.innerHTML = atex; //設置回答數組的數據到回答的節點
setTimeout(function () {//延時1s回答 逼真 打字須要時間
dialog.appendChild(ali);//插入節點
status.style.display = "none";//隱藏div
dialog.scrollTop = dialog.scrollHeight - dialog.offsetHeight - 2;//計算可視窗口須要滾動的距離。
}, 1000);
} else {//爲空提示
alert("內容不能爲空!");
}
}
but.onclick = function () {//按鈕點擊事件
creat();
}
texInput.onkeydown = function (ev) {//鍵盤迴車
if (ev.keyCode == 13) {
creat();
}
return false;//清除默認行爲
}
}
</script>
</head>
<body>
<h1>宅男必備機器人</h1>
<div id="auto" class="msg-list">
<ul>
<!--<li>機器人</li>
<li class="active">我方</li>-->
</ul>
<textarea></textarea>
<button>提交</button>
<div class="status">對方正在輸入...</div>
</div>
</body>
</html>