效果如下:
话不多说~直接上代码!
HTML+CSS:
<style>
#wrapper {
width: 400px;
height: 500px;
border: 2px solid blue;
margin: 20px 0;
overflow: auto;
}
img {
width: 60px;
border-radius: 50%;
transform: translateY(17px);
}
input {
width: 300px;
height: 30px;
}
button {
width: 90px;
height: 30px;
}
</style>
<body>
<div id="wrapper"></div>
<input type="text" id="inp">
<button id="btn">发送</button>
<script src="text.js"></script>
</body>
text.js:
//获取相关标签
var _wrapper=document.querySelector("#wrapper");
var _inp=document.querySelector("#inp");
var _btn=document.querySelector("#btn");
//定义数组存储头像
var img=['./img/1.webp', './img/2.webp', './img/3.webp', './img/4.webp', './img/5.webp', './img/6.webp'];
//定义数组存储名字
var names = ['顺其自然', '慈悲为怀', '清心寡欲', '好运莲莲', '与世无争', '四大皆空'];
var i=0;
_btn.onclick=function(){
//随机的头像和姓名的下标
var index=Math.floor(Math.random()*6);
//随机名字
var id=names[index];
//随机头像
var imgs=img[index];
//获取用户输入的input的值;
var msg = _inp.value;
if(i%2==0){
//判断为偶数行时,文本靠右,文本=文本+头像+名字:+信息
_wrapper.innerHTML=
`<div style=text-align:left;>${_wrapper.innerHTML}<img src="${imgs}"><span>${id}</span>:${msg}<br></div>`;
}else{
//判断为奇数行时,文本靠左,文本=文本+信息+:名字+头像
_wrapper.innerHTML=
`<div style=text-align:right;>${_wrapper.innerHTML}${msg}:<span>${id}</span><img src="${imgs}"><br></div>`;
}
//点击发送后清空input
_inp.value="";
//增加行
i++;
}
以上就是简易聊天框的实现过程
批注都在代码里啦~