自定義滾動條樣式-transition無效
阿新 • • 發佈:2018-09-05
swe 我們 contain not dep bar ray 就是 overflow
問題
需求是自定義滾動條樣式,然後2秒內無操作隱藏滾動條。
2s內隱藏比較麻煩,不能用css實現,只能監聽容器的touch事件,然後給滾動條加個opacity: 0
的class。
.class::-webkit-scrollbar{ width: 10px; -webkit-transition: all 1s; transition: all 1s; } .class::-webkit-scrollbar-thumb{ border-radius: 5px; background-color: gray; } .class.hide::-webkit-scrollbar{ opacity: 0; }
需要在touch事件觸發2s後給container加上.hide的class。為了實現過渡效果,我加了transition: all 1s
。然而並沒有用
stackoverflow上也有相關提問 https://stackoverflow.com/questions/19230289/use-transition-on-webkit-scrollbar
解決
事實證明,scrollbar上面是不允許用transition的。
Short answer: No, it‘s not possible to use transition on a ::-webkit-scrollbar
不過網友給了很多hack方案。
我下面介紹一種。如果不想聽可以直接看例子:https://codepen.io/waterplea/pen/dVMopv
解決原理
簡單來說就是在元素上加transition,而不是在scrollbar偽類上。
利用-webkit-scrollbar-thumb的color繼承自該元素,該元素transition color的時候,滾動條的color也會transition。剩下的就是用color實現一個滾動條了。
.class::-webkit-scrollbar-thumb{
border-radius: 5px;
box-shadow: inset 0 0 0 5px; // 用box-shadow模擬滾動條
}
.class { -webkit-transition: all 1s; transition: all 1s; } .class.hide { color: transparent!important; }
如果該元素有文字咋辦?
我們用該元素的color屬性做滾動條的顏色,那該元素的字體就要換個了。
.class {
text-shadow: 0 0 #fff;
}
用text-shadow指定字體顏色。
over!
自定義滾動條樣式-transition無效