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

一、实践踩坑

项目使用mpvue开发

1. scroll-view默认是不滚动的。。所以要先设置scroll-x="true"或者scroll-y="true"

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

?
1
2
3
4
scroll-view {
   width : 100% ;
   white-space : nowrap ; // 不让它换行
  }

3. 然后在定宽元素里边添加子容器:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 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。此时正确姿势如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 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就基本如我所愿了,大概长这样:

二、隐藏滚动条

在网上搜了很多,都是说加上这段代码就可以:

?
1
2
3
4
5
6
7
8
9
10
11
/*隐藏滚动条*/
 
::-webkit-scrollbar{
 
   width : 0 ;
   
   height : 0 ;
   
   color : transparent ;
 
}

或者有的人说这样子:

?
1
2
3
4
5
6
7
/*隐藏滚动条*/
 
::-webkit-scrollbar{
 
   display : none ;
 
}

然而两种方法我都试过,scroll-view的滚动条依然存在。。测试机型是安卓机子。

但是用display: none这种方法是可以隐藏掉页面的滚动条的,就是scroll-view的滚动条没隐藏掉。

后来,在小程序社区看到官方人员这样子解答:

是的,就是这种野路子。当然 ,它下面的评论里也有人提供了另一种解决思路方法,但我还是选择了官方说的那种野路子方法。传送门

实现思路就是,在scroll-view外边再包一个容器,它的高度小于scroll-view的高度,这样就会截掉滚动条,达到隐藏了滚动条的效果。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 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;
  }

大概意思是这样:

猜你喜欢

转载自www.cnblogs.com/lorelei123/p/10688834.html