繁体   English   中英

仅使用Javascript模仿@keyframes规则

[英]Imitating @keyframes rule using Javascript only

我正在尝试创建一个使用百分比来获取数字的函数。 想法是这样的:0%:100px 50%:200px 75%:210px

因此,当我以25%的百分比运行我的功能时,它将0和50混合在一起,同样高于50%。

这听起来有点复杂,总的想法是用JS创建一些东西,这样可以减少从0到100%的数字

我已经尝试过使用常规百分比计算,但它并不适用于3个或更多变量。

因此,如果您不介意我冒昧地将您的百分比转换为JSON对象:

let input = {
  0: 100,
  50: 200,
  75: 210,
};

如果我们假设百分比总是整数,那么我们可以做这样的事情:

let output = {};
let previous = null;
// for each whole percent
for(let keyPercent in input)
{
  // cast to number
  let currPercent = parseFloat(keyPercent);
  // get value of percent
  let currValue = input[currPercent];
  if (currValue != null) { // if value is present
    if (previous != null) { // and previous value is not null
      // find the step size (valDiff) / (percentDiff)
      let step = (currValue - previous.value) / (currPercent - previous.percent);
      // count to multiply by step
      let count = 0;
      // this produces the percent value for every step between previous.percent and currPercent
      for (let prevPercent = previous.percent; prevPercent <= currPercent; prevPercent += 1) {
        output[prevPercent] = previous.value + (step * count);
        count += 1;
      }
    }
    // set previous value
    previous = { percent: currPercent, value: currValue };
  }
}
console.log(output);

这输出的内容如下:

0: 100
1: 102
2: 104
...
48: 196
49: 198
50: 200
51: 200.4
52: 200.8
...
73: 209.2
74: 209.6
75: 210

如果您需要任何澄清,请告诉我。

注意:注释是在代码中完成的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM