自定义滚动条样式-transition无效

版权声明:未经允许,请勿盗用 https://blog.csdn.net/qq_37916164/article/details/84067661

问题
需求是自定义滚动条样式,然后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。然而并没有用

解决
事实证明,scrollbar上面是不允许用transition的。
Short answer: No, it’s not possible to use transition on a ::-webkit-scrollbar

解决原理
简单来说就是在元素上加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指定字体颜色。

猜你喜欢

转载自blog.csdn.net/qq_37916164/article/details/84067661