微信小程序scroll-view横向滚动的实践踩坑及隐藏其滚动条的实现

41次阅读

共计 1870 个字符,预计需要花费 5 分钟才能阅读完成。

一、实践踩坑
项目使用 mpvue 开发
1. scroll-view 默认是不滚动的。。所以要先设置 scroll-x=”true” 或者 scroll-y=”true”

2. 在 scroll-view 里面添加定宽元素,超过 scroll-view 宽度(设置了 100%,即屏幕宽度 ) 后,它竟然换行了。所以要 scroll-view 的样式要这样设置:
scroll-view {
width: 100%;
white-space: nowrap; // 不让它换行
}

3. 然后在定宽元素里边添加子容器:
// html 大概长这样
<scroll-view scroll-x=”true”>
<div class=”tab-item”>
<img class=”content-icon”/>
<div></div>
</div>
<div class=”tab-item”>
<img class=”content-icon”/>
<div></div>
</div>
<div class=”tab-item”>
<img class=”content-icon”/>
<div></div>
</div>
</scroll-view>

// css 相应就大概长这样
scroll-view {
display: flex;
flex-wrap: nowrap;
}
.tab-item {
display: flex;
justify-content: center;
width: 25%;

}
然后发现.tab-item 并没有排在一行上。。说明 scroll-view 和.tab-item 都设置 display: flex 无效?无奈之下,只好在它外边再包一层,然后样式设置 display: inline-block。此时正确姿势如下:
// html
<div class=”scroll-view-container”>
<scroll-view scroll-x=”true” :scroll-into-view=”toView”>
<div class=”tab-container”>
<div class=”tab-item”>
<img class=”content-icon”/>
<div></div>
</div>
</div>
</scroll-view>
</div>

// css 变成这样子
scroll-view {
width: 100%;
white-space: nowrap; // 不让它换行
}

.tab-container {
display: inline-block;
width: 25%;
}

.tab-item {
display: flex;
flex-direction: column;
align-items: center;

}

到这里,scroll-view 就基本如我所愿了,大概长这样:

二、隐藏滚动条
在网上搜了很多,都是说加上这段代码就可以:
/* 隐藏滚动条 */

::-webkit-scrollbar{

width: 0;

height: 0;

color: transparent;

}
或者有的人说这样子:
/* 隐藏滚动条 */

::-webkit-scrollbar{

display: none;

}

然而两种方法我都试过,scroll-view 的滚动条依然存在。。测试机型是安卓机子。
但是用 display: none 这种方法是可以隐藏掉页面的滚动条的,就是 scroll-view 的滚动条没隐藏掉。
后来,在小程序社区看到官方人员这样子解答:

是的,就是这种野路子。当然,它下面的评论里也有人提供了另一种解决思路方法,但我还是选择了官方说的那种野路子方法。传送门实现思路就是,在 scroll-view 外边再包一个容器,它的高度小于 scroll-view 的高度,这样就会截掉滚动条,达到隐藏了滚动条的效果。
// scss
.scroll-view-container {// 包裹 scroll-view 的容器
height: $fakeScrollHeight;
overflow: hidden; // 这个设置了就能截掉滚动条啦
scroll-view {
width: 100%;
white-space: nowrap;
}
}

.tab-container {// 我这里是用.tab-container 来撑开 scroll-view 的高度,所以高度在它上面设置, 加上 padding,那么它就会比外层容器(.scroll-view-container)要高
display: inline-block;
width: 26%;
height: $fakeScrollHeight;
padding-bottom: $scrollBarHeight;
}
大概意思是这样:

正文完
 0