使用jquery向下滚动后,表未固定在顶部

时间:2018-03-22 09:49:35

标签: javascript jquery html css

实际上我在向下滚动后使用jquery来停止表,但这不能正常工作。有时它的振动而不是在滚动之后固定但有时工作正常。



$(document).ready(function () {
        $(window).scroll(function () {
            if ($(document).scrollTop() > 200) {  $('.reportAction').addClass('reportActionFixed');
            }
            else {
                $('.reportAction').removeClass('reportActionFixed');
            }
        })
});

  .box{ height: 200px; }

.reportActionFixed{position: fixed;
    top: 0px;
    left: 0px;
    width: 100%;
    z-index: 1000;
    background: #fff;
    padding: 0px;
    border-bottom: 1px solid #ccc;}

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>

<div class="box"></div>

<table class="table reportAction">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>Doe</td>
        <td>john@example.com</td>
      </tr>
      <tr>
        <td>Mary</td>
        <td>Moe</td>
        <td>mary@example.com</td>
      </tr>
      <tr>
        <td>July</td>
        <td>Dooley</td>
        <td>july@example.com</td>
      </tr>
    </tbody>
  </table>


<img src="https://flyflytravel.com/images/destinacije/maldivi/840x500/maldivi840x500.jpg">
&#13;
&#13;
&#13;

如果我正在更改scrollTop distance,那么它的工作正常但在我给scrolltop 200时无法正常工作。任何人都可以解决它?

顺便说一句,我在我的代码中使用了CSS的简单最新jquery。

提前致谢。

1 个答案:

答案 0 :(得分:3)

在CSS类position: sticky中设置reportActionFixed。如果您不需要表格上方的空白区域,请在CSS类height: 0px中创建box或完全删除它。

Here is a fiddle.