滚动到div时添加类,在滚动到JQuery中的另一个div时删除类

时间:2014-11-28 18:26:16

标签: javascript jquery html

Fiddle Example

我试图通过添加类fixed_header滚动到表格并在滚动表格时删除该类来使表头变得固定。

以下代码可以在滚动到#start_body

时添加该类
$(document).ready(function(){
  $(window).resize(function() {
    if($(window).width() < 525) {
      var s_body = $('#start_body').offset();
      var e_body = $('#end_body').offset();
      $(document).scroll(function () {
        var y = $(this).scrollTop();
        if(y >= s_body.top){
          $('table thead').addClass('fixed_header');
        }
        else if(y < e_body.top) // what condition should I use?
        {
          $('table thead').removeClass('fixed_header');
        }
    })
  }
 }).resize();
})

但是如何在滚动到#end_body时删除课程?

HTML:

<div class='jk'></div><div id='start_body'><h3>Start</h3>
 <table>
    <thead><tr><th>Age</th><th>Gender</th></tr></thead>
    <tbody>
        <tr><td>12</td><td>M</td></tr>
        <tr><td>14</td><td>F</td></tr>
        <tr><td>12</td><td>M</td></tr>
        <tr><td>14</td><td>F</td></tr>   
        ..........
    </tbody>
 </table>    
</div>
<div id='end_body'>
    <h3>End</h3>
</div>

1 个答案:

答案 0 :(得分:1)

JSFiddle

if(y >= s_body.top && y < e_body.top){
      $('table thead').addClass('fixed_header');
    }
    else 
    {
      $('table thead').removeClass('fixed_header');
    }