JS .animate()无法在Firefox / IE中运行

时间:2016-02-21 01:54:27

标签: javascript html firefox gecko

所以我试图给div做一个动画,但我不确定我在这里做错了什么。以下代码适用于最新的Safari和Chrome,但不适用于Internet Explorer和Firefox。 在Firefox上,错误为el.animate is not a function 有什么建议/解决方案吗?

var slowMo = false;
var dur = slowMo ? 5000 : 500;

function $(id) {
  return document.getElementById(id);
}

var players = {};

var hue = 0;

function addTouch(e) {
  var el = document.createElement('div');
  el.classList.add('ripple');
  var color = 'hsl(' + (hue += 70) + ',100%,50%)';
  el.style.background = color;
  var trans = 'translate(' + e.pageX + 'px,' + e.pageY + 'px) '
  console.log(trans);
  var player = el.animate([{
    opacity: 0.5,
    transform: trans + "scale(0) "
  }, {
    opacity: 1.0,
    transform: trans + "scale(2) "
  }], {

    duration: dur

  });
  player.playbackRate = 0.1;
  players[e.identifier || 'mouse'] = player;

  document.body.appendChild(el);
  player.onfinish = function() {
    if (!document.querySelector('.ripple ~ .pad')) each(document.getElementsByClassName('pad'), function(e) {
      e.remove();
    });
    el.classList.remove('ripple');
    el.classList.add('pad');

  }
}

function dropTouch(e) {
  players[e.identifier || 'mouse'].playbackRate = 1;
}

function each(l, fn) {
  for (var i = 0; i < l.length; i++) {
    fn(l[i]);
  }
}
document.body.onmousedown = addTouch;
document.body.onmouseup = dropTouch;

document.body.ontouchstart = function(e) {
  e.preventDefault();
  each(e.changedTouches, addTouch);
};
document.body.ontouchend = function(e) {
  e.preventDefault();
  each(e.changedTouches, dropTouch);
};

var el = document.body;

function prevent(e) {
  e.preventDefault();
}

el.addEventListener("touchstart", prevent, false);
el.addEventListener("touchend", prevent, false);
el.addEventListener("touchcancel", prevent, false);
el.addEventListener("touchleave", prevent, false);
el.addEventListener("touchmove", prevent, false);




function fakeTouch() {
  var touch = {
    pageX: Math.random() * innerWidth,
    pageY: Math.random() * innerHeight,
    identifier: 'fake_' + Math.random() + '__fake'
  }
  addTouch(touch);
  var length = Math.random() * 1000 + 500;
  setTimeout(function() {
    dropTouch(touch);
  }, length)
  setTimeout(function() {
    fakeTouch();
  }, length - 100)

}
if (location.pathname.match(/fullcpgrid/i)) fakeTouch(); //demo in grid
.ripple {
  position: absolute;
  width: 100vmax;
  height: 100vmax;
  top: -50vmax;
  left: -50vmax;
  border-radius: 50%;
}
body {
  overflow: hidden;
}
.pad {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
<div class="pad"></div>

Code thanks to Kyle

1 个答案:

答案 0 :(得分:0)

所以我采用了不同的方法来实现相同的结果。我认为这个更直接,适用于所有浏览器。

https://jsfiddle.net/cbrmuxcq/1/

虽然有一个小问题,但我不确定是什么原因造成的。如果我不等待(通过使用endUpdates()),则不会发生转换,而是通过设置超时。如果有人能发现问题,我会修复小提琴并相应地更新我的答案。