微信小程序scroll-view橫向滾動的實踐踩坑及隱藏其滾動條的實現

一、實踐踩坑

項目使用mpvue開發

1. scroll-view默認是不滾動的。。所以要先設置scroll-x="true"或者scroll-y="true"

clipboard.png

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就基本如我所願了,大概長這樣:

clipboard.png

二、隱藏滾動條

在網上搜了很多,都是說加上這段代碼就可以:

/*隱藏滾動條*/

::-webkit-scrollbar{

    width: 0;
    
    height: 0;
    
    color: transparent;

}

或者有的人說這樣子:

/*隱藏滾動條*/

::-webkit-scrollbar{

    display: none;

}
  1. 然而兩種方法我都試過,scroll-view的滾動條依然存在。。測試機型是安卓機子。
  2. 但是用display: none這種方法是可以隱藏掉頁面的滾動條的,就是scroll-view的滾動條沒隱藏掉。
  3. 後來,在小程序社區看到官方人員這樣子解答:

clipboard.png

是的,就是這種野路子。當然 ,它下面的評論裏也有人提供了另一種解決思路方法,但我還是選擇了官方說的那種野路子方法。傳送門
實現思路就是,在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;
  }

大概意思是這樣:

clipboard.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章