核心代码
- 设置滚动属性默认自动滚动到底部:
// 获取设置了滚动属性的div标签
const div = document.getElementById('conversationalDiv');
// 设置滚动的顶点坐标为滚动的总高度
div.scrollTop = div.scrollHeight;
应用场景
场景:实现对话框,默认展示最新的对话内容文章来源:https://www.toymoban.com/news/detail-722524.html
文章来源地址https://www.toymoban.com/news/detail-722524.html
- 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;
}
到了这里,关于【JS】设置滚动属性默认自动滚动到底部(overflow:scroll;)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!