简体   繁体   中英

Making a Div fixed on Scrolling

How to make a div fixed on detection of Scrolling by the Users.
Example: Right Sidebar of Facebook, it gets stuck when a certain scroll position is attained.

position:fixed is the answer.
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..

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; to it to make it appear on the sam place even after scrolling.

More on CSS positioning

It seams you are looking for position: sticky; .

Learn more: https://css-tricks.com/position-sticky-2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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