离子:获取离子含量中当前可见的项目

Yos*_*sho 7 lazy-evaluation angularjs ionic-framework

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

我需要知道哪些项目对用户可见.

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

Yos*_*sho 5

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

它正在重新发明轮子,但是有效.

当我加载项目时,我调用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
  };
});
Run Code Online (Sandbox Code Playgroud)