Show/hide div on page scroll

2020-08-01 06:10发布

问题:

I have a table with a lot of rows, which makes the page scroll. There's some other content above the table. I would like to add a functionality using jQuery, to show div across the page top, as soon as the table scrolls to the point, where the top row disappears above the top border of the screen.

I assume I'll add a div with position set to fixed, but how do I know when the top row moves above the fold?

<div id="topDiv" style="display: none; position: fixed; top: 0"></div>

<table>
<thead>
<tr>
   <th></th>
<tr>
</thead>
<tbody>
<tr>
   <td></td>
<tr>
...
</tbody>
</table>

回答1:

This is what you are looking for. Sticky Div:

http://blog.yjl.im/2010/01/stick-div-at-top-after-scrolling.html

Implementation example: http://www.nkhome.com/kestrel/compare-kestrels.php



回答2:

You can use something like this

$(window).scroll(function(e){ 
  $el = $('#topDiv'); 
  if ($(this).scrollTop() > 200 && $el.css('position') != 'fixed'){ 
    $el.css({'position': 'fixed', 'top': '0px'}); 
  } 
});

This check if the window has scrolled above 200px and fixes the topDiv



标签: jquery