首页 前端知识 前端开发之简易聊天框

前端开发之简易聊天框

2024-04-08 11:04:22 前端知识 前端哥 658 238 我要收藏

页面效果展示

HTMl代码布局页面

<body>
<div class="container">
<div class="showcon" id="showcon"></div>
<input type="text" id="msg" />
<button onclick="send()">发送</button>
</div>
</body>
复制

CSS样式部分

<style>
.container {
width: 600px;
text-align: center;
padding: 20px 0;
margin: 0 auto;
background-color: green;
}
.container .showcon {
width: 550px;
height: 400px;
padding: 10px;
overflow: auto;
background-color: #fff;
margin: 0 auto 10px;
}
#msg {
width: 500px;
height: 40px;
}
.container button {
width: 50px;
height: 40px;
vertical-align: middle;
}
</style>
复制

JavaScript部分

<script>
var i = 0;
function send() {
var _ipt = document.getElementById('msg');
// 判断输入内容不为空
if (_ipt.value === '') {
alert('输入内容不能为空');
return;
}else{
i++;
}
var _div = document.querySelector(".showcon");
// 定义字体颜色
var r = randColor();
var g = randColor();
var b = randColor();
// 输入内容在左侧还是右侧 判断 i是奇数聊天内容在左侧 i是偶数聊天内容在右侧
if (i % 2 === 1) {
_div.innerHTML += `<p style='text-align:left;color:rgb(${r},${g},${b})'>${_ipt.value}</p>`;
} else {
_div.innerHTML += `<p style='text-align:right;color:rgb(${r},${g},${b})'>${_ipt.value}</p>`;
}
_ipt.value = ''; //清空输入框的输入内容
}
// math.floor() 函数用来返回数字的下舍整数,即它总是将数值向下舍入为最接近的整数
function randColor() {
return Math.floor(Math.random() * 256);
}
</script>
复制

转载请注明出处或者链接地址:https://www.qianduange.cn//article/4584.html
标签
评论
发布的文章

JQuery中的load()、$

2024-05-10 08:05:15

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!