文章目录
- 核心代码
- 应用场景
核心代码
- 设置滚动属性默认自动滚动到底部:
// 获取设置了滚动属性的div标签
const div = document.getElementById('conversationalDiv');
// 设置滚动的顶点坐标为滚动的总高度
div.scrollTop = div.scrollHeight;
应用场景
场景:实现对话框,默认展示最新的对话内容
- react 实现:
import { Input } from 'antd';
import { useState } from 'react';function() {const [loading, setLoading] = useState(false);// 创建 dt dd 标签const createTag = (type, innerHTML) => {const dl = document.getElementById('conversationalDl');const tag = document.createElement(type);// 添加标签内容tag.innerHTML = innerHTML;if (dl) {// 向dl插入标签dl.appendChild(tag);}const div = document.getElementById('conversationalDiv');if (div) {// 设置滚动到最底部div.scrollTop = div.scrollHeight;}};const onConversationalSearch = async (val) => {// 创建dt标签,表示用户输入的内容createTag('dt', val);setLoading(true);try {const data = await getText(val);// 测试数据:// const data = "I'm good, how are you?"// 创建dd标签,表示另一边输入的内容createTag('dd', data);} catch (error) {}setLoading(false);};return ( <><div id = "conversationalDiv" className = {styles.conversationalDiv} ><dl id = "conversationalDl" / ></div> <Input.Search placeholder = "Your sentence here..."allowClear enterButton = "Send"onSearch = {onConversationalSearch}/> </>)
}
- 所需用到的css样式
.conversationalDiv {height: 256px;width: 100%;border: 1px solid #e5e7eb;overflow: auto;
}
.conversationalDiv dl {display: flex;flex-direction: column;align-items: flex-end;padding: 12px;
}
.conversationalDiv dl dt {display: inline-block;background-color: #2563eb;color: #fff;padding: 8px 12px;border-radius: 20px;margin-bottom: 10px;
}
.conversationalDiv dl dd {display: inline-block;background-color: #f9fafb;color: #000;padding: 8px 12px;border-radius: 20px;place-self: start;margin-bottom: 10px;
}