view横向滚动的实践踩坑及隐藏其滚动条的实现

项目使用mpvue开发

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

view横向滚动的实践踩坑及隐藏其滚动条的实现

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

scroll-view { width: 100%; white-space: nowrap; // 不让它换行 }

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

// html大概长这样 <scroll-view scroll-x="true"> <div> <img/> <div></div> </div> <div> <img/> <div></div> </div> <div> <img/> <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> <scroll-view scroll-x="true" :scroll-into-view="toView"> <div> <div> <img/> <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就基本如我所愿了,大概长这样:

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; }

大概意思是这样:

view横向滚动的实践踩坑及隐藏其滚动条的实现

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/33458d54785ea15bcd2817c375225747.html