2016-06-14 178 views
2

所以,我試圖根據它們的滾動位置來動畫元素(按順序和獨立)。基於滾動位置的動畫

目標是循環遍歷每個元素,並根據用戶滾動位置更改它的旋轉。現在,每個項目的輪換總是相同的。這怎麼能實現?

這裏是一個小提琴:https://jsfiddle.net/nfquerido/wy84pLud/

這是循環功能:

var _items = function() { 
    forEach(items, function(item) { 
     var scrollTop = _scrollTop(), 
      elementTop = item.offsetTop, 
      documentHeight = _getDocumentHeight(), 
      elementHeight = _getElementHeight(item), 

      // Transform the item based on scroll 
      rotation = (scrollTop/(documentHeight - windowHeight) * 360), 
      transform = 'rotate(' + rotation + 'deg)'; 

     // Elements off the top edge. 
     if (scrollTop > elementTop) { 
      item.classList.add('scrolling'); 
      item.style.webkitTransform = transform; 
     } else { 
      item.classList.remove('scrolling'); 
      item.style.webkitTransform = null; // Reset the transform 
     } 
    }); 
}; 

我會很感激香草的JavaScript建議只請!

+0

這裏的解決方案@Annihilator以下建議的小提琴:https://jsfiddle.net/nfquerido/wy84pLud/5/ – nfq

回答

2

我覺得這是你要找的修復:我加你的旋轉VAR的分配上面這個權利

// Transform the item based on scroll 
    rotationFactor = Math.max(0, scrollTop - elementTop), 
    rotation = (rotationFactor/(documentHeight - windowHeight) * 360), 

更換之後,他們會各自相對偏移旋轉: )

錯誤是,唯一的變化/影響變量的旋轉是你的scrollTop,而這只是在文檔級。 要對元級影響我們也希望包括差異:)

+0

輝煌,感謝@ Annihlator。我知道我以某種方式使用元素頂部偏移量(因此將var留在原地;)),但我無法弄清楚。 – nfq