无限滚动与粘滞日期标记

时间:2015-03-30 15:19:41

标签: jquery html infinite-scroll sticky jsrender

我创建的页面无限滚动事件,按时间顺序按日期分组。每个日期标记可以有几个后续事件。向下滚动特定日期的事件时,这些事件的日期标记将粘贴到页面顶部。当达到新的日期标记时,旧的日期标记会滚动页面,新的日期标记会粘在其位置上。

从页面底部向上滚动向上滚动时出现问题。日期不会以相反的顺序始终位于页面顶部。出了什么问题?

请查看我的代码和演示,如下:



$(function() {
  function addContainers() {
    var nextN = $('.marker-container').length + 1;
    var containers = []

    // Each container has 2 sections now
    for (var i = nextN; i <= nextN + 1; i++) {
      containers.push({
        number: i
      })
    };

    $(".wrapper").html($(".wrapper").html() + $("#template").render(containers));
  }

  function registerMarkers() {
    var collection = $('.marker');

    $.each(collection, function(index, marker) {
      // The last element always does not have a limit
      if (index == collection.length - 1) {
        if ($.isScrollToFixed(marker)) $(marker).trigger('remove.ScrollToFixed');
        $(marker).scrollToFixed();
      } else {
        var nextMarker = $(collection[index + 1]);

        // Skip current, if it and the following one are already registered
        if ($.isScrollToFixed(marker) && $.isScrollToFixed(nextMarker)) return true;
        // On this stage we have all unregistered markers and the last registered one, which precedes the first unregistered marker.

        var nextMarkerC = nextMarker.parent(); // For offsets we rely on stable position of marker container

        $(marker).scrollToFixed({
          limit: nextMarkerC.offset().top - 100
        });
      }
    });
  }

  addContainers();
  registerMarkers();

  $(window).bind('scroll', function() {
    // If we reached the end of window
    if (document.body.scrollHeight - $(this).scrollTop() <= $(this).height()) {
      addContainers();
      registerMarkers();
    }
  });
});
&#13;
body {
  margin-top: 10px;
}
.wrapper {
  width: 500px;
  margin: 0 auto;
}
.marker {
  position: absolute; // This is important!
  margin: 0 auto;
  width: 200px;
  height: 98px;
  border: 3px dashed red;
  text-align: center;
  font-size: 20px;
}
.section {
  margin: 0;
  text-align: center;
  font-size: 40px;
  height: 800px;
  border: 3px #666 dashed;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script src="http://www.jsviews.com/download/jsrender.min.js"></script>
<script src="http://bigspotteddog.github.io/ScrollToFixed/jquery-scrolltofixed-min.js"></script>

<body>

  <script id="template" type="text/x-jsrender">
    <div class="marker-container">
      <div class="marker">Date {{>number}}</div>
    </div>
    <div class="section">One event</div>
    <div class="section">Another event</div>
  </script>

  <div class="wrapper"></div>
</body>
&#13;
&#13;
&#13;

See code and demo on JSFiddle

0 个答案:

没有答案