簡體   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