我有一个变量正在增加,比方说从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>
答案 0 :(得分:6)
类似的东西:
// 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
将需要更改为其他值,或传递最大值。
答案 1 :(得分: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
答案 2 :(得分:0)
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 MyVar
答案 3 :(得分:0)
这就是我可能会这样做的方式,这样你就可以一次“动画”多个对象,而不会在剧本中做太多改变:
HTML:
<div class="mover" data-start="0" data-end="400" data-prop="margin-left"></div>
jQuery的:
var p = 0;
function start(){
$('.mover').each(function(){
var $t = $(this);
$t.css($t.data('prop'),$t.data('start')+($t.data('end')-$t.data('start'))/100*p);
});
if(p<100){
p++;
setTimeout(start,Math.round(Math.random()*500));
}
}
start();