HarmonyOS中利用overflow属性实现横向滚动失效的解决方法
HarmonyOS中利用overflow属性实现横向滚动失效的解决方法
既然要用到overflow属性,那我们先来看看overflow属性究竟有什么作用(菜鸟教程上的定义)。
1、overflow属性实现竖直滚动
废话不多说,上代码
one.hml
<div class="container"> <block for="{{arrs}}"> <div class="boxview"> <text>{{$item}}</text> </div> </block></div>
one.css
.container { display: flex; flex-direction: column; width: 100%; overflow: scroll; /*在需要滚动的盒子中添加overflow属性 设为scroll即可实现滚动效果。 配合flex弹性布局的flex-direction属性 (column)按竖直方向排列 即可实现竖直滚动效果*/}.boxview{ width: 100%; height: 12%; display: flex; justify-content: center; align-items: center; border-bottom: 1vr solid black;}
one.js
export default { data: { arrs:[] },//生命周期函数 页面加载时触发 onInit() { //利用for循环添加数据 for(let i = 0; i < 100; i++){ this.arrs.push("第" + i + "行"); } }}
实现效果
2、overflow属性实现横向滚动失效
基于竖直滚动,我们很容易认为只需设置盒子flex-direction:row;
但是现实并非如此,滚动布局失效了!!!
css
.container { display: flex; flex-direction: row;/*此处改为row 使其水平排列*/ width: 100%; overflow: scroll;}/*以下见1中代码*/
实现效果
可以发现滚动布局失效了 所有列都挤在了页面当中!!!
查看鸿蒙开发文档,发现了端倪(但这里所说并不完全正确,详情见横向布局失效解决方法)
3、横向布局失效解决方法
3.1、overflow方法(改进版)
整个页面不支持横向滚动。但是局部页面可以实现overflow:scroll 横向布局。并非鸿蒙开发文档中的只支持纵向
two.hml
<div class="container"> <div class="top2"> <block for="{{arrs}}"> <div class="boxview"> <text>{{$item}}</text> </div> </block> </div></div>
two.css
.container { display: flex; flex-direction: column;}.boxview{ width: 30%; display: flex; justify-content: center; align-items: center; border-right: 1px solid black;}.top2{ height: 30%; display: flex; overflow: scroll;}
two.js
export default { data: { arrs:[] }, onInit() { for(let i = 0; i < 100; i++){ this.arrs.push("第" + i + "列"); } }}
实现效果
3.2、list和list-item组件实现横向滚动
three.hml
<div class="container"> <div class="top1"> <list class="listview"> <block for="{{arrs}}"> <list-item> <div class="boxview"> <text>{{$item}}</text> </div> </list-item> </block> </list> </div></div>
three.css
.container { display: flex; flex-direction: column;}.top1{ height: 30%;}.listview{ display: flex; flex-direction: row;}.boxview{ width: 30%; display: flex; justify-content: center; align-items: center; border-right: 1px solid black;}
three.js
export default { data: { arrs:[] }, onInit() { for(let i = 0; i < 100; i++){ this.arrs.push("第" + i + "列"); } }}
实现效果
与overflow方式实现效果一致,此处不再展开。