如何让 div 贴在屏幕顶部?
在本文中,我们将了解如何制作一个粘在屏幕顶部的粘性元素。在这里,我们使用 div 贴在屏幕顶部。我们将通过使用以下两种方法来了解它的实现。
方法一:使用 position 属性的粘性值
position 属性的“sticky”值将元素设置为使用“相对”位置,除非它穿过页面的特定部分,然后使用“固定”位置。被卡住的元素的垂直位置也可以在'top'属性的帮助下进行修改。可以给它一个值“0px”以使元素在视口顶部不留空间,或者进一步增加以从视口顶部留出空间。
示例:此示例说明了使用 position 属性来粘贴到元素的顶部。
HTML
GeeksforGeeks
Sticky Element
How to make make a div stick
to the top of the screen once
it’s been scrolled to?
A Computer Science portal for geeks.
It contains well written, well thought
and well explained computer science and
programming articles, quizzes and
practice/competitive programming/company
interview Questions.
This is div will stick to the top
when it has been scrolled past
A Computer Science portal for geeks.
It contains well written, well thought
and well explained computer science and
programming articles, quizzes and
practice/competitive programming/company
interview Questions.
HTML
GeeksforGeeks
How to make make a div stick
to the top of the screen once
it’s been scrolled to?
A Computer Science portal for geeks.
It contains well written, well thought
and well explained computer science and
programming articles, quizzes and
practice/competitive programming/company
interview Questions.
This is div will stick to the top
when it has been scrolled past
A Computer Science portal for geeks.
It contains well written, well thought
and well explained computer science and
programming articles, quizzes and
practice/competitive programming/company
interview Questions.
输出:
方法 2:将 div 设置为滚动过去后卡住
此方法试图模拟“位置:粘性”方法。该元素被设置为“固定”或“相对”,具体取决于用户是否滚动过该元素。
首先确定要卡住的元素并计算其在页面上的当前位置。这是通过添加元素相对于当前滚动位置的视口的位置来完成的。
getBoundingClientRect()方法返回一个 DOMReact 对象,其'top'值可用于获取相对于视口的位置。通过使用window.pageYOffset属性可以找到当前的垂直滚动位置。添加这两个值将为我们提供页面上元素的位置,而不管当前滚动位置如何。
然后使用一个新函数覆盖 onscroll 方法,以计算当前滚动位置并将其与页面上元素的位置进行比较。如果垂直滚动超过元素的位置,则 position 属性设置为'fixed' ,并且'top'属性的值为'0px' 。否则,位置设置为'relative' ,并使用'initial'值重置'top'属性。
每当用户滚动经过元素时,这将比较并使元素粘住。
示例:此示例说明了 div 在滚动过去后卡住的设置。
HTML
GeeksforGeeks
How to make make a div stick
to the top of the screen once
it’s been scrolled to?
A Computer Science portal for geeks.
It contains well written, well thought
and well explained computer science and
programming articles, quizzes and
practice/competitive programming/company
interview Questions.
This is div will stick to the top
when it has been scrolled past
A Computer Science portal for geeks.
It contains well written, well thought
and well explained computer science and
programming articles, quizzes and
practice/competitive programming/company
interview Questions.
输出: