实现一个简易聊天机器人

一. 画出聊天机器人的界面

1. 拆解网页(HTML)

效果图
  • 标题区是一个大的块元素包含一个题目
  • 对话区是一个列表的展现形式
  • 输入区是一个输入框加一个按钮
代码如下
<!-- HTML -->
<html>

<head>
    <title>Chatbot</title>
</head>

<body>
    <div class="chatbot">
        <header>
            <!-- <header> 元素用于展示介绍性内容,通常包含一组介绍性的或是辅助导航的实用元素。 -->
            <h2>聊天机器人小二黑</h2>
        </header>
        <ul class="message-list">
            <li class="message-list__item message-list__item-chatbot">
                <div>您好,小主人,我是聊天机器人小二黑,赶快和我聊天试试吧!</div>
            </li>
            ...
            <li class="message-list__item message-list__item-chatbot">
                <div>真棒,吃的好快呀</div>
            </li>
        </ul>
        <div class="input-area">
            <!-- 这个输入框需要输入多行文本,普通的输入框是不能换行的,所以用textarea这个元素 -->
            <textarea></textarea>
            <button>发送</button>
        </div>
    </div>
</body>

</html>
效果图
效果图

2. 布局(CSS)

2.1 整体区域
* {
    background-color: white;
    /* 设定下全部元素的 padding 和 margin,这样做的目的是清楚元素的   默认 padding 和 margin,方便布局 */
    margin: 0;
    padding: 0;
}

.chatbot {
    width: 480px;
    /* 整体区域居中 */
    margin: auto;
}
2.2 标题区
  • flex布局,justify-content、align-items均设置为center
header {
    height: 50px;
}

header h2 {
    height: 50px;
    display: flex;
    height: 100%;
    justify-content: center;
    align-items: center;
}
2.3 对话区
  • 机器人和用户的对话列表元素均采用flex布局
  • 设置用户的对话列表元素的flex-directionrow-reverse使得用户的对话靠右
.message-list {
    height: 400px;
    padding: 10px;
}

.message-list__item-chatbot,
.message-list__item-user {
    margin-bottom: 10px;
    display: flex;
}

.message-list__item-user {
    /* flex-direction 属性指定了内部元素是如何在 flex 容器中布局的,定义了主轴的方向(正方向或反方向)。
    row-reverse表现和row相同,但是置换了主轴起点和主轴终点 */
    flex-direction: row-reverse;
    /* justify-content:flex-end也可以实现同样的效果,但只有一个子元素的时候表现一样
    row-reverse不仅会将子元素的位置全部靠向右边,还会将子元素的排列顺序反转*/
}
2.3 输入区
  • 布局设置为flex,且设置输入框的flex-grow1
.input-area {
    display: flex;
    height: 100px;
}

.input-area textarea {
    /* flex-grow 属性定义弹性盒子项(flex item)的拉伸因子。 */
    flex-grow: 1;
}
实现效果

3. 样式美化(CSS)

...

.message-list {
    background-color: white;
    height: 400px;
    padding: 10px;
    /* 默认的列表标签是有样式的,这个属性就是把列表标签的默认样式给去除掉*/
    list-style: none;
    font-size: 16px;
}
.message-list__item-robot div,
.message-list__item-user div {
    line-height: 20px;
    /* word-break属性指定了怎样在单词内断行。 */
    word-break: break-all;
    /* word-wrap属性允许将长单词打断并包装到下一行。 */
    word-wrap: break-word;
    border-radius: 8px;
    padding: 10px;
    max-width: 200px;
}

...

.input-area textarea {
    /* 去除轮廓属性,一般输入框聚焦,按钮点击,都会有默认的轮廓*/
    outline: none;
    padding: 6px;
    line-height: 20px;
    flex-grow: 1;
    /* 去除边框属性 */
    border: none;
    border-bottom-left-radius: 3px;
    font-size: 16px;
}

.input-area button {
    /* cursor属性定义鼠标指针悬浮在元素上方显示的鼠标光标 */
    cursor: pointer;
    width: 40px;
    border: none;
    outline: none;
    background-color: #008cee;
    color: white;
    border-bottom-right-radius: 3px;
}
实现效果