javascript - requestFrameAnimation 使用持续时间时断断续续

标签 javascript php html css

我正在为 HTMLElement 编写一个 fadeIn 函数,动画可以工作,但目前有点不稳定。它所做的是将淡入动画从 0 不透明度设置为 1,它还使用 requestFrameAnimation 在一段时间内进行动画处理,这就是为什么它可能如此不稳定,有人可以帮助我让我的动画运行得更流畅吗?示例位于 codepen.io看看标题 fadeIn 就明白我的意思了

fadeIn: function(duration) {

    var el = this.$el,
      duration,
      end = 0;

    el.style.opacity = 0;
    el.style.display = "block";

    var step = function() {
      var current = +new Date(),
          remaining = end - current;
      if(remaining < 60) {
        if(el) {
          end = current + duration;

          var val = parseFloat(el.style.opacity);
          if (!((val += .1) > 1)) {
            el.style.opacity = val;
          }
        } else {
          return;
        }
      }

      requestAnimationFrame(step);
    };

    step();
  },

最佳答案

最流畅的方法是使用 CSS 过渡。但如果你想使用纯 Javascript,你可以这样做

function fadeIn(dom, duration) {
  let start = null;

  const step = (end) => {
    if (start === null) start = end;
    let dt = end - start;
    dom.style.opacity = Math.min(1, dt / duration);
    if (dt < duration) requestAnimationFrame(step);
  }

  requestAnimationFrame(step);
}

function fadeOut(dom, duration) {
  let start = null;

  const step = (end) => {
    if (start === null) start = end;
    let dt = end - start;
    dom.style.opacity = Math.max(0, 1 - dt / duration);
    if (dt < duration) requestAnimationFrame(step);
  }

  requestAnimationFrame(step);
}

fadeIn(document.getElementById('your_dom'), 2000);

关于javascript - requestFrameAnimation 使用持续时间时断断续续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55718588/

相关文章:

javascript - 值不通过 Javascript 传递,而是直接传递给 PHP

javascript - ESP8266 服务于 HTML+js

javascript - Highcharts - 需要高级工具提示功能

javascript - 将值存储到 localStorage 的顺序是同步的吗?

javascript - CasperJS 不能要求下划线

session - PHP session 处理错误

javascript - 使用与 Java 中相同的 PHP 加密方法

javascript - tinyMCE.get ("content") 未定义

javascript - “onsubmit”未运行 javascript 函数

php - Sphinx 部分单词搜索,版本 2.2.4