我有一个变量在增加,比如说从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>发布于 2012-08-08 00:07:47
例如,如果顶部和底部分别为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发布于 2012-08-08 00:05:51
类似于:
// b - beginning position
// e - ending position
// i - your current value (0-99)
function getTween(b, e, i) {
return b + ((i/99) * (e-b));
}如果您的增量值将不同于0-99,则函数中的硬编码99将需要更改为其他值,或传递最大值。
发布于 2012-08-08 00:10:16
var MyVar = 0, Max = 99;
setInterval(increaseMyVar,30)//Call increaseMyVar every 30ms
function increaseMyVar()//MyVar Will go from 0 - 99
{
MyVar = ++MyVar % Max;
}
//Do whatever you want with MyVarhttps://stackoverflow.com/questions/11849654
复制相似问题