滚动条闪动解决方案
翻页、切换排序方式时,都会向后端发起数据请求,然后前端拿到数据更新 DOM,在更新 DOM 的时候,会出现短暂的跳动,滚动条会在更新 DOM 的时候因为容器内容高度不够(loading 动画高度不够)而消失很短暂的时间,然后 DOM 更新好后,又出现。
- 这里不能强制设置内容高度设得很大,因为用户浏览器高度未知,有些用户浏览器高度很大,在切换时,滚动条依然会消失一段时间。
- 也不能设置
overflow-y: scroll;,因为当数据量小的时候,不需要滚动条。
所以在进行设计的时候,就要考虑滚动条的存在,预留好滚动条的宽度!!
# 方案一:去掉滚动条。
.content-wp{
-ms-overflow-style: none; // IE 10+
scrollbar-width: none; // Firefox
&::-webkit-scrollbar{ //Chrome safari
display: none;
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# 方案二:定位
给会发生跳动的元素加上相对定位,设置left:0; width:calc(100vw - 12px);,这里的 12px 是滚动条宽度。
定位的话,就不会产生跳动了。
# 滚动条宽度计算
// 采用单例实现
let scrollBarWidth
export default function () {
if (scrollBarWidth !== undefined) return scrollBarWidth
const outer = document.createElement('div')
outer.style.overflow = 'scroll'
outer.style.visibility = 'hidden'
outer.style.width = '100px'
outer.style.height = '100%'
outer.style.position = 'absolute'
outer.style.top = '-9999px'
document.body.appendChild(outer)
const widthNoScroll = outer.offsetWidth
const inner = document.createElement('div')
inner.style.width = '100%'
outer.appendChild(inner)
const widthWithScroll = inner.offsetWidth
outer.parentNode.removeChild(outer)
scrollBarWidth = widthNoScroll - widthWithScroll
return scrollBarWidth
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
上次更新: 2023/12/16, 09:22:46