Allen's blog Allen's blog
首页
面经
算法 (opens new window)
分类

Allen

前端CV工程师
首页
面经
算法 (opens new window)
分类
  • Javascript

  • TypeScript

  • CSS

  • Vue

  • React

  • 框架和构建工具

  • 工具库

  • 常见业务场景

    • 事件委托
    • 滚动条闪动解决方案
      • 滚动条宽度计算
    • 列表拖拽排序
    • linear-gradient背景渐变色
    • 表格组件数据加载,排序等
    • 时间业务
    • 滚动加载
    • 文件下载
  • Bug

  • 项目实战

  • 前端
  • 常见业务场景
Allen
2023-03-30
目录

滚动条闪动解决方案

翻页、切换排序方式时,都会向后端发起数据请求,然后前端拿到数据更新 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

# 方案二:定位

给会发生跳动的元素加上相对定位,设置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
上次更新: 2023/12/16, 09:22:46
事件委托
列表拖拽排序

← 事件委托 列表拖拽排序→

最近更新
01
rollup使用配置文件rollup.config.ts打包
12-08
02
package.json导出类型
12-08
03
关键问题方案
11-17
更多文章>
Theme by Vdoing | Copyright © 2023-2023 Allen | Github
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式