簡體   English   中英

確定何時在滾動父容器中查看子容器的百分比

[英]Determine when a percentage of a child container is in view in a scrolling parent container

我已經在紙上玩了一兩個小時,但是似乎有點卡住了。 考慮到我有一個父容器的寬度為100%(適合其父寬度,可以是任意大小的像素)的情況,該子容器包含子容器的大小占其寬度的百分比(對於此示例為90%),該怎么辦我可以確定子容器的可見時間百分比(例如80%)? 最終結果是確定您當前使用的子容器為1/4或3/4等。子容器的數量是可變的,有時可能是1,可能是100。

它的父容器的子容器寬度可以變化,但是對於每個子容器,它們始終是相同的,例如,所有90%的父容器或所有100%寬度。

我繪制了一個粗略的圖表,希望可以使它更容易理解。

在此處輸入圖片說明

因此,在上面的示例圖片中,我們當前位於幻燈片1的3中。但是,如果我們向右滾動,現在看到80%的綠色容器,我們將位於幻燈片2的3等中。黑色在這種情況下,容器是父容器。

最終的數學解決方案將在JavaScript中實現。

基本上,您想獲取幻燈片容器的當前位置,然后將其除以父容器的寬度。

如下所示:Math.round(Math.abs(currentPosition)/ containerWidth);

可能的最低值為零,它將與第一張幻燈片相對應。

請參閱我的評論,以獲取有關此操作的示例。

您可以使用以下函數計算可見的孩子的百分比:

function calculateVisiblePercentage(childLeft, childWidth, containerOffset, containerWidth){

  // Position of the left side of the child, 
  // or the container left side if the child 
  // starts before the left side of the container
  var x0 = Math.max(containerOffset, childLeft);

  // Position of the right side of the child,
  // or the container right side if the child
  // ends after the right side of the container
  var x1 = Math.min(containerOffset + containerWidth, childLeft + childWidth);

  if (x1 < x0){
    // It's not visible
    return 0;
  }

  var pixelsVisible = x1 - x0;

  // Percentage
  return pixelsVisible * 100 / childWidth;
};

其中childLeft是孩子左側的位置。 例如,如果子級寬度為100px,則第一個子級為0,第二個子級為100,依此類推。其中containerOffsetcontainerOffset的位置/滾動。

您可以在此JSFiddle中看到一個基本的工作示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM