File tree Expand file tree Collapse file tree 5 files changed +427
-20
lines changed Expand file tree Collapse file tree 5 files changed +427
-20
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ title : 滚动条右侧出现白色占位条
3
+ date : 2025-5-27 10:52
4
+ description : 关于 js 切换样式的前端笔记
5
+ # image: "../public/assets/images/arch1.jpg"
6
+ category : 记录
7
+ tags :
8
+ - 前端
9
+ - css
10
+ published : true
11
+ sitemap : true
12
+ ---
13
+
14
+ ## 问题
15
+
16
+ 我用 css + js 实现了一个汉堡菜单的组件,其中当汉堡菜单弹出并关闭后,滚动条右侧会出现异常的白色占位条。这个占位条无法被 f12 选中。
17
+
18
+ 正常的滚动条:
19
+ ![ OAuth2授权] ( ../public/assets/images/scroll1.png )
20
+ 出现在滚动条右侧的异常的白色占位条:
21
+ ![ OAuth2授权] ( ../public/assets/images/scroll2.png )
22
+
23
+ 我认得这个占位条,它是在页面没有滚动条时占位,以保证页面切换时宽度一致的。想要启用它只需设置:
24
+
25
+ ``` css
26
+ html {
27
+ overflow-y : scroll ; /* 总是显示滚动条*/
28
+ }
29
+ ```
30
+
31
+ 按理来说,我的页面中已经存在了滚动条,这个占位条是不该存在的。
32
+
33
+ ## 解决方案
34
+
35
+ 发现问题存在于:
36
+
37
+ ``` js
38
+ // 打开菜单
39
+ function toggleMenu () {
40
+ ...
41
+ body .style .overflow = sidebar .classList .contains (" active" )
42
+ ? " hidden"
43
+ : " auto" ;
44
+ }
45
+
46
+ // 关闭菜单
47
+ function closeMenu () {
48
+ ...
49
+ body .style .overflow = " auto" ;
50
+ }
51
+ ```
52
+
53
+ 此处,我使用了` body.style.overflow ` 来直接设置滚动条样式,在关闭菜单时,突如其来的` body.style.overflow = "auto"; ` 使得浏览器出现渲染不同步。
54
+ 使用 js 直接修改样式是很坏的,浏览器很多时候无法响应。更好的做法是使用类名携带样式,再使用 js 进行类名的切换:
55
+
56
+ ``` js
57
+ // 打开菜单
58
+ function toggleMenu () {
59
+ ...
60
+ body .classList .toggle (" no-scroll" , sidebar .classList .contains (" active" ));
61
+ }
62
+ // 关闭菜单
63
+ function closeMenu () {
64
+ ...
65
+ body .classList .remove (" no-scroll" );
66
+ }
67
+ ```
68
+
69
+ ``` css
70
+ /* 此处的 is:inline 是在astro组件中使用的,用于将css直接传递给浏览器,不使用astro的话不需要 */
71
+ <style is:inline>
72
+ .no-scroll {
73
+ overflow-y : hidden ;
74
+ }
75
+ </style >
76
+ ```
77
+
78
+ 然后白色占位条就顺利消失了
Load Diff This file was deleted.
You can’t perform that action at this time.
0 commit comments