两个值之间的插值或"补间"(但不是动画)

Son*_*man 2 javascript jquery

我有一个变量,正在增加让我们说从0到99.

然后我有一个div,我想以增加变量的相同速率移动,但我只想定义运动的两端(例如从上到下移动,我只定义最上面的位置和最下面的位置) .其余应该在主变量将其值从0更改为99时自动插值.

我得到的所有搜索结果都与动画有关.但这并不完全是动画,因为如果变量没有改变,div不应该移动.你会如何在javascript中做到最好?

编辑:一些模拟代码(可能有语法错误):

<html>

<body>

<div id="increase"></div>
<div id="move"></div>

</body>

</html> 

 <script>
var counter =0;
var topValue =50;
var bottomValue =150;
var interpolatedValue


$('#increase').click(){
counter++; 
}

$('#move').css(){
top: interpolatedValue; //this should be an interpolation between 50 and 150 based on the current counter value
}


</script>
Run Code Online (Sandbox Code Playgroud)

小智 8

就像是:

// b - beginning position
// e - ending position
// i - your current value (0-99)
function getTween(b, e, i) {
    return b + ((i/99) * (e-b));
}
Run Code Online (Sandbox Code Playgroud)

如果您的递增值将不同于0-99,则99函数中的硬编码将需要更改为其他值,或传递最大值.


dqh*_*cks 5

例如,如果顶部和底部分别为400和600,您可以使用一些简单的数学计算基于变量的位置.

var theVariable = 25; // 1 to 100
var top = 400;
var bottom = 600;
var distance = bottom - top;
var position = top + ((theVariable / 100) * distance); // 450
Run Code Online (Sandbox Code Playgroud)