关于CSS:具有溢出支持的位置粘性Polyfill

position sticky polyfill with overflow support

本问题已经有最佳答案,请猛点这里访问。

我在应用程序中的容器中使用position: sticky,该容器使用overflow属性显示滚动条。 我搜索了一个支持这种情况的polyfill,但到目前为止还没有任何运气。

有人知道支持oveflow的这种polyfill / shim吗?

问候


我使用了一个名为stickyfill的position: sticky polyfill来做到这一点。

即使在本机支持position: sticky的浏览器上,您也只需告诉polyfill即可完成工作。

这也是Codepen上的演示

1
2
Stickyfill.forceSticky()
Stickyfill.add(document.querySelectorAll('[data-sticky]'));
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
55
56
57
58
59
60
body {
  padding: 50vh 2rem 100vh 2rem;
  font-size: 0.625rem;
  font-family: monospace;
  color: white;
}

.heading {
  display: flex;
}
.heading h2 {
  flex: 1;
  color: #444;
  font-weight: bold;
  padding: 1rem;
}

main {
  display: flex;
}

.parent {
  flex: 1;
  margin: 0 3px;
  padding: 1rem;
  display: flex;
  flex-flow: row nowrap;
  align-items: flex-start;
  overflow: visible;
}
.parent-sticky .sticky {
  position: -webkit-sticky;
  position: sticky;
}
.parent-overflow {
  height: 1000px;
  overflow: hidden;
}
.parent-worst .content, .parent-worst .sticky {
  background: linear-gradient(to bottom, tomato, red);
}
.parent-best .content, .parent-best .sticky {
  background: linear-gradient(to bottom, #11ee11, #22cc22);
  color: black;
}

.sticky {
  width: 50%;
  top: 1rem;
  margin-bottom: 1rem;
  padding: 0.3rem;
  background: linear-gradient(to bottom, #999, #555);
}

.content {
  flex: 1;
  height: 2500px;
  padding: 0.3rem;
  background: linear-gradient(to bottom, #999, #555);
}
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
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
<script src="https://cdnjs.cloudflare.com/ajax/libs/stickyfill/2.1.0/stickyfill.min.js">

\toverflow: hidden;
\toverflow: visible;
\toverflow: visible;
\toverflow: hidden;


<main>
\t
\t\t
\t\t\tposition: sticky native with overflow-hiding parent
\t\t
\t\t
\t\t\tdoesn't work at all
\t\t
\t

\t
\t\t
\t\t\tposition:stickynative
\t\t
\t\t
\t\t\tWorks fine in"newer" browsers
\t\t
\t

\t
\t\t
\t\t\tstickyfill without overflow-hiding parent
\t\t
\t\t
\t\t\tworks fine in most browsers
\t\t
\t

\t
\t\t
\t\t\tstickyfill with overflow-hiding parent
\t\t
\t\t
\t\t\tworks fine in most browsers
\t\t
\t
</main>