javascript - 加载内容时阻止无限滚动跳转到页面末尾

标签 javascript php jquery jquery-isotope infinite-scroll

我在我的网站上使用同位素实现了无限滚动,但在加载帖子时遇到问题。帖子加载得很好,但假设我向下滚动以加载更多帖子,但我仍在查看已经存在的帖子,每当加载新帖子时,无限滚动就会跳转到页面底部。即使加载了更多帖子,如何才能停止这种行为并保持页面上的位置?

我的脚本--

$(function () {
        var selectChoice, updatePageState, updateFiltersFromObject,
            $container = $('.isotope');
        ////////////////////////////////////////////////////////////////////////////////////
        /// EVENT HANDLERS
        ////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////
        // Mark filtering element as active/inactive and trigger filters update
        $('.js-filter').on( 'click', '[data-filter]', function (event) {
          event.preventDefault();
          selectChoice($(this), {click: true});
          $container.trigger('filter-update');
        });
        //////////////////////////////////////////////////////
        // Sort filtered (or not) elements
        $('.js-sort').on('click', '[data-sort]', function (event) {
          event.preventDefault();
          selectChoice($(this), {click: true});
          $container.trigger('filter-update');
        });
        //////////////////////////////////////////////////////
        // Listen to filters update event and update Isotope filters based on the marked elements
        $container.on('filter-update', function (event, opts) {
          var filters, sorting, push;
          opts = opts || {};
          filters = $('.js-filter li.active a:not([data-filter="all"])').map(function () {
            return $(this).data('filter');
          }).toArray();
          sorting = $('.js-sort li.active a').map(function () {
            return $(this).data('sort');
          }).toArray();
          if (typeof opts.pushState == 'undefined' || opts.pushState) {
            updatePageState(filters, sorting);
          }
          $container.isotope({
            filter: filters.join(''),
            sortBy: sorting
          });

        });
        //////////////////////////////////////////////////////
        // Set a handler for history state change
        History.Adapter.bind(window, 'statechange', function () {
          var state = History.getState();
          updateFiltersFromObject(state.data);
          $container.trigger('filter-update', {pushState: false});
        });
        ////////////////////////////////////////////////////////////////////////////////////
        /// HELPERS FUNCTIONS
        ////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////
        // Build an URI to get the query string to update the page history state
        updatePageState = function (filters, sorting) {
          var uri = new URI('');
          $.each(filters, function (idx, filter) {
            var match = /^\.([^-]+)-(.*)$/.exec(filter);
            if (match && match.length == 3) {
              uri.addSearch(match[1], match[2]);
            }
          });
          $.each(sorting, function (idx, sort) {
            uri.addSearch('sort', sort);
          });
          History.pushState(uri.search(true), null, uri.search() || '?');
        };
        //////////////////////////////////////////////////////
        // Select the clicked (or from URL) choice in the dropdown menu
        selectChoice = function ($link, opts) {
          var $group = $link.closest('.btn-group'),
              $li = $link.closest('li'),
              mediumFilter = $group.length == 0;
          if (mediumFilter) {
            $group = $link.closest('.js-filter');
          }

          if (opts.click) {
            $li.toggleClass('active');
          } else {
            $li.addClass('active');
          }
          $group.find('.active').not($li).removeClass('active');
          if (!mediumFilter) {
            if ($group.find('li.active').length == 0) {
              $group.find('li:first-child').addClass('active');
            }
            $group.find('.selection').html($group.find('li.active a').first().html());
          }
        };
        //////////////////////////////////////////////////////
        // Update filters by the values in the current URL
        updateFiltersFromObject = function (values) {
          if ($.isEmptyObject(values)) {
            $('.js-filter').each(function () {
                selectChoice($(this).find('li').first(), {click: false});
            });
            selectChoice($('.js-sort').find('li').first(), {click: false});
          } else {
            $.each(values, function (key, val) {
              val = typeof val == 'string' ? [val] : val;
              $.each(val, function (idx, v) {
                var $filter = $('[data-filter=".' + key + '-' + v + '"]'),
                    $sort = $('[data-sort="' + v + '"]');
                if ($filter.length > 0) {
                  selectChoice($filter, {click: false});
                } else if ($sort.length > 0) {
                  selectChoice($sort, {click: false});
                }
              });
            });
          }
        };
        ////////////////////////////////////////////////////////////////////////////////////
        /// Initialization
        ////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////
        // Initialize Isotope
$container.imagesLoaded( function(){
        $container.isotope({
  masonry: { resizesContainer: true },
          itemSelector: '.item',
          getSortData: {
 date: function ( itemElem ) {
      var date = $( itemElem ).find('.thedate').text();
      return parseInt( date.replace( /[\(\)]/g, '') );
    },
area: function( itemElem ) { // function
      var area = $( itemElem ).find('.thearea').text();
      return parseInt( area.replace( /[\(\)]/g, '') );
    },
price: function( itemElem ) { // function
      var price = $( itemElem ).find('.theprice').text();
      return parseInt( price.replace( /[\(\)]/g, '') );
    }
          }
        });

var total = $(".next a:last").html();
var pgCount = 1;
var numPg = total;

    // jQuery InfiniteScroll Plugin.
    $container.infinitescroll({
 contentSelector  : '.isotope',
 speed : 'fast',
behavior: 'simplyrecipes',
         navSelector  : '#pagi',    // selector for the paged navigation 
        nextSelector : '#pagi a.next',  // selector for the NEXT link (to page 2)
        itemSelector : '.item',     // selector for all items you'll retrieve
        animate: true,
debug: true,
        loading: {
selector: '#infscr-loading',
            finishedMsg: 'No more content to load.'
        }
    },
    // Trigger Masonry as a callback.
    function( newElements ) {
        pgCount++;

        if(pgCount == numPg) {
            $(window).unbind('.infscr');
            $container.isotope('reload');
            $container.append( newElements ).isotope( 'appended', newElements, true );
            $('#infscr-loading').find('em').text('No more content to load.');
            $('#infscr-loading').animate({
                opacity: 1
            }, 200);
            setTimeout(function() {
                $('#infscr-loading').animate({
                    opacity: 0
                }, 300);
            });
        } else {
            loadPosts(newElements);
        }
    }); 
});

function loadPosts(newElements) {
    // Hide new posts while they are still loading.
    var newElems = $( newElements ).css({ opacity: 0 });
    // Ensure that images load before adding to masonry layout.
    newElems.imagesLoaded(function() {
        // Show new elements now that they're loaded.
        newElems.animate({ opacity: 1 });
        $container.isotope( 'appended', newElems, true );      
    });
}
        //////////////////////////////////////////////////////
        // Initialize counters
        $('.stat-count').each(function () {
          var $count = $(this),
              filter = $count.closest('[data-filter]').data('filter');
          $count.html($(filter).length);
        });
        //////////////////////////////////////////////////////
        // Set initial filters from URL
        updateFiltersFromObject(new URI().search(true));
        $container.trigger('filter-update', {pushState: false});
      }); 
});

最佳答案

您可以从覆盖无限滚动的默认动画属性开始

$container.infinitescroll({
    animate:false, //this does just that
});

关于每个请求(或某些请求)的重复条目, 它与您的后端有关,即您偏移数据的方式

Infinite Scroll works great with page numbers i.e it Sends 2,3,4,5,6 ... So For every request its sends that request.

我认为您正在使用页面偏移,并且您可能最终会得到重复的条目。

如果您使用 php 作为接收端......这可能会有所帮助

//In your Controller
$temp = ( $page_offset * $per_page );
$offset = $temp - $per_page ;

//In your model
$this->db->query("SELECT * FROM GALLERY OFFSET $offset limit 10");

这只是一个粗略的想法,希望对您有所帮助。

如果是的话,请注意查看Sticky Bubble ? - 免费游戏 Google Play .

干杯:)

关于javascript - 加载内容时阻止无限滚动跳转到页面末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34760396/

相关文章:

php - 如何使用eloquent根据表列和hasMany关系的计数返回记录

jquery - 如何使这个消失/重新出现的 AJAX 加载 GIF 停止移动其他元素?

Javascript 滑动 Div 问题

javascript - 更改数据表中搜索框的 DOM 元素位置

javascript - 将未知数量的参数传递给 JavaScript 函数

javascript - 将字符串变量转换为数组

php - 我的 GAHelloWorld 实现逻辑有什么问题?

javascript - Backbone.js 应用程序方法不是很可扩展 - 嵌套 View

javascript - Angularjs 并使用包含 __proto__ 的数组进行选择

php - 覆盖外连接失败的记录的默认值