Ionic:获取ion-content中当前可见的项目

Ionic: Get the currently visible items in ion-content

我的应用程序中有一个长长的可滚动 ion-content 区域,其中填充了使用 collection-repeat 的项目。

我需要知道用户可以看到哪些项目。

我无法使用$ionicScrollDelegate.getScrollPosition来计算答案,因为每个项目都有不同的高度(项目高度是按项目计算的)。

最后我自己计算了元素的总高度,并通过查询 .scroll 元素的 translateY 值,我可以找出哪个项目在滚动的可见部分.

这是在重新发明轮子,但确实有效。

当我加载项目时,我调用 ScrollManager.setItemHeights(heights)heights 是以像素为单位的项目高度数组),并获取当前可见项目的索引:ScrollManager.getVisibleItemIndex()

angular.module("services")
.service('ScrollManager', function() {
  var getTranslateY, getVisibleItemIndex, setItemHeights, summedHeights;
  summedHeights = null;
  setItemHeights = function(heights) {
    var height, sum, _i, _len;
    summedHeights = [0];
    sum = 0;
    for (_i = 0, _len = heights.length; _i < _len; _i++) {
      height = heights[_i];
      sum += height;
      summedHeights.push(sum);
    }
  };

  // returns the style translateY of the .scroll element, in pixels
  getTranslateY = function() { 
    return Number(document.querySelector('.scroll').style.transform.match(/,\s*(-?\d+\.?\d*)\s*/)[1]);
  };

  getVisibleItemIndex = function() {
    var i, y;
    y = -getTranslateY();
    i = 0;
    while (summedHeights[i] < y) {
      i++;
    }
    return i;
  };

  return {
    setItemHeights: setItemHeights,
    getVisibleItemIndex: getVisibleItemIndex
  };
});