简体   繁体   English

使 Div 固定在滚动上

[英]Making a Div fixed on Scrolling

How to make a div fixed on detection of Scrolling by the Users.如何使 div 固定在用户检测滚动时。
Example: Right Sidebar of Facebook, it gets stuck when a certain scroll position is attained.示例:Facebook 的右侧边栏,到达某个滚动位置时它会卡住。

position:fixed is the answer. position:fixed就是答案。
But you can always look at a website's source if you want to know how they do something. 但是,如果您想知道网站的工作方式,则可以随时查看网站的来源。 Very educational! 很有教育意义!

Monitor whether or not we're scrolling. 监视我们是否正在滚动。

if($(window).scrollTop() > 0){
  //we're scrolling our position is greater than 0 from the top of the page.
  $("#element").css({'position' : 'fixed'});
}

* EDIT * 编辑

Do it without jQuery.. 不用jQuery就可以做到。

if(window.scrollTop() > 0){
  document.getElementById('element').style.position="fixed";
}

我遇到过这篇文章,其中介绍了一种解决方案https://www.virendrachandak.com/techtalk/make-a-div-stick-to-top-when-scrolled-to/

Not sure if this is what you mean? 不知道这是什么意思吗?

But you can add the CSS-propery position: fixed; 但是您可以添加CSS属性位置:fixed; to it to make it appear on the sam place even after scrolling. 使其即使在滚动后仍显示在sam位置上。

More on CSS positioning 有关CSS定位的更多信息

It seams you are looking for position: sticky;它接缝你正在寻找的position: sticky; . .

Learn more: https://css-tricks.com/position-sticky-2/了解更多: https : //css-tricks.com/position-sticky-2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM