基于滚动位置的动画

时间:2016-06-14 13:36:17

标签: javascript

所以,我试图根据滚动位置动画元素(顺序和独立)。

目标是遍历每个元素,并根据用户滚动位置更改它的旋转。现在,每个项目的轮换始终是相同的。如何实现这一目标?

这是一个小提琴: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
        }
    });
};

我非常感谢vanilla JavaScript建议!

1 个答案:

答案 0 :(得分:2)

我认为这是您正在寻找的解决方案:

我在旋转var的分配上面添加了这个:

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

更换后,每个人都得到相对偏移轮次:)

错误是旋转的唯一更改/影响变量是scrollTop,而这只是在文档级别。 为了影响元素级别,我们还希望包含这种差异:)