首页 > 解决方案 > 如何在 Safari 中使用 .animate javascript?获得未定义不是一个函数

问题描述

我正在尝试随机为多个叶子设置动画。这是我的代码:

var leafs = document.querySelectorAll(".leaf");

leafs.forEach(function(leaf) {

        var angle = parseInt(leaf.getAttribute("data-angle")),
            posY = parseInt(leaf.getAttribute("data-top")),
            posX = parseInt(leaf.getAttribute("data-left")),
            directionX = Math.random() < 0.5 ? -1 : 1,
            directionY = Math.random() < 0.5 ? -1 : 1,
            newposX = directionX * Math.round(Math.random()*10) + posX,
            newposY = directionY * Math.round(Math.random()*10) + posY,
            angleRotation = Math.round(Math.random()*20) + angle;
            //keyframe = {transform: ['translate3d(' + posX + 'px,' + posY + 'px, 0px) rotate(' + angle + 'deg)', 'translate3d(' + newposX + ',' + newposY + ', 0px) rotate(' + angleRotation + ')']};

        console.log(leaf);

        leaf.animate([
            {
             transform: 'translate3d(' + posX + 'px,' + posY + 'px, 0px) rotate(' + angle + 'deg) '
            },
            {
             transform: 'translate3d(' + newposX + 'px,' + newposY + 'px, 0px) rotate(' + angleRotation + 'deg)'
            }
        ], {
            iterations: Infinity,
            direction: 'alternate',
            easing: 'ease-in-out',
            duration: 3000
        });
    });

在 Firefox 和 chrome 中它工作正常。在 safari 中出现以下错误,我不知道如何处理。我正在使用香草javascript。

TypeError: undefined is not a function (near '...leaf.animate...')

更新

原来我需要一个 polyfill 或 Jquery。

PolyFill 可以在这里找到:web-animations-js

标签: javascriptanimation

解决方案


看看web-animations-js,谷歌提供的 w3 polyfill。它有点过时,但至少适用于前 99% 的浏览器上的大多数 Web Animations API 功能。


推荐阅读