js实现简单的自动回复机器人,(利用数组的index的绑定)

<!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>

猜你喜欢

转载自www.cnblogs.com/sun-shine1229/p/10687890.html