[英]Imitating @keyframes rule using Javascript only
I'm trying to create a function that uses percentage to get a number. 我正在尝试创建一个使用百分比来获取数字的函数。 The idea is to have something like this: 0%: 100px 50%: 200px 75%: 210px
想法是这样的:0%:100px 50%:200px 75%:210px
So when I run my function at a percentage like 25% it blends 0 and 50 together, same for above 50%. 因此,当我以25%的百分比运行我的功能时,它将0和50混合在一起,同样高于50%。
It sounds kind of complicated, the overall idea is to create something using JS only that will ease the numbers going from 0 to 100% 这听起来有点复杂,总的想法是用JS创建一些东西,这样可以减少从0到100%的数字
I've tried using regular percentage calculation, yet it doesn't really work for 3 or more variables. 我已经尝试过使用常规百分比计算,但它并不适用于3个或更多变量。
So if you don't mind I've taken the liberty of turning your percentage into a JSON object: 因此,如果您不介意我冒昧地将您的百分比转换为JSON对象:
let input = {
0: 100,
50: 200,
75: 210,
};
We can then do something like this if we assume percentages are always whole numbers: 如果我们假设百分比总是整数,那么我们可以做这样的事情:
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);
this outputs something along the lines of: 这输出的内容如下:
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
Let me know if you need any clarification. 如果您需要任何澄清,请告诉我。
Note: comments are made in code 注意:注释是在代码中完成的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.