移动端内滚动效果

最近看到一个移动端顶部固定,主体部分滚动的效果。但是它不是简单的fixed定位,如果这样滚动条在外侧,即整个页面。

而接下来介绍的这种方法,滚动的是主体部分,可以看到滚动条不会到顶部。

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
html *{
padding: 0;
margin: 0;
}
.container {
height: 100%;
overflow: hidden;
}
.header {
height: 50px;
background-color: aquamarine;
}
.main {
position: absolute;
top: 50px;
bottom: 0;
left: 0;
right: 0;
background-color: rgb(243, 243, 138);
overflow-y: scroll;
}
.main div {
height: 400px;
}
</style>
</head>

<body>
<div class="container">
<div class="header"></div>
<div class="main">
<div>ddd</div>
<div>ddd</div>
<div>ddd</div>
<div>ddd</div>
</div>
</div>
</body>

</html>

在chrome的f12移动调试模式,可以看到效果。

这里有一篇文章讲这种效果的。 移动端实现内滚动的4种方案 - 知乎

img

新增一种内滚动的方式,之前写react的时候遇到的。样式如下设置:

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>test inner scroll</title>
<style>
*{
padding: 0;
margin: 0;
}
html,body{
height: 100%;
width: 100%;
position: relative;
overflow: hidden;
}
div#root{
height: 100%;
width: 100%;
position: relative;
display: flex;
}
div.main{
/*height:100%;*/
width: 100%;
overflow-y: scroll;
}
header{
height: 100px;
background-color: antiquewhite;
position: fixed;
width: 100%;
top: 0;
}
section,footer{
height: 1000px;
}
section{
background-color: aquamarine;
}
</style>
</head>
<body>
<div id="root">
<div class="main">
<header></header>
<section></section>
<footer></footer>
</div>
</div>
</body>
</html>

可以看到滚动条,但是实际的滚动条从header下边就开始了,被header挡住了,一般这种情况配合透明色或者浅色的背景header效果不错。这种内滚动中,html,body充当的窗口,而div#root有点特殊,他需要设置display:flex来使后代元素的overflow-y:auto;起作用,个中原理我认为是flex盒子的高度均由内容撑起,并且创建BFC。还有一种方法就是不设置flex而把后代元素的height:100%设置,这样也可以实现。

img

打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!

给阿姨来一杯卡普基诺~

支付宝
微信