横向滚动
基于 flex 实现横向滚动。

完整 Demo: https://github.com/fangmd/wiki-demo/blob/master/horizontal-scroll/index.html
已测试环境:
- PC Chrome
功能#
- 元素水平排列,不换行
- 元素宽度正常
- 内容超出范围时,可以水平滚动
- 隐藏滚动条
实现#
基本布局 React:
const App = () => { const [data, setData] = React.useState(['红烧肉', '肉夹馍'] const addItem = () => { console.log('add item'); data.push(`${data.length}`) setData([...data])
return ( <div> <button onClick={addItem}>Add Item</button> <div className='h-scroll-container hide-scrollbar'> { data && data.map((i, index) => { return <div className="item" key={index}>{i}</div> }) } </div> </div> )}样式:
<style> .h-scroll-container { display: flex; /* width: 100vw; */ overflow: scroll; flex-direction: row; } /* 隐藏滚动条 */ .hide-scrollbar::-webkit-scrollbar { display: none; /* Chrome Safari */ } .hide-scrollbar { scrollbar-width: none; /* firefox */ -ms-overflow-style: none; /* IE 10+ */ } .item { /* 重要,避免 item 受到 flex 影响,被压缩 */ flex: none; height: 30px; line-height: 30px; border-radius: 20px; padding: 0 10px; background: rgb(192, 222, 135); margin-right: 10px; }</style>h-scroll-container设置flex布局,并且支持滚动,宽度可以按需设置item设置flex: none;可以避免 item 宽度被压缩
横向滚动扩展:内容少的时候靠右#

完整 Demo: https://github.com/fangmd/wiki-demo/blob/master/horizontal-scroll/index2.html
主要设置 flex-direction: row-reverse; 实现内容靠右
.h-scroll-container { display: flex; /* width: 100vw; */ overflow: scroll; flex-direction: row-reverse; /* 修改 */}数据添加的时候将数据添加到头部:
data.unshift(`${data.length}`)