本文介绍了内插或“补间"在两个值之间(但不设置动画)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,假设从0增加到99.

I have a variable that is increasing let's say from 0 to 99.

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

Then I have a div that I want to move at the same rate of the increasing variable but I only want to define the two ends of the movement (for example moving from top to down, I only define the topmost position and the downmost position). The rest should be interpolated automatically while the main variable is changing it's value from 0 to 99.

我得到的所有搜索结果都与动画相关.但这并不是完全动画,因为如果变量未更改,则div不应移动.您如何用javascript做到最好?

All the search results I got were related to animating. But this is not exactly animating since the div should not move if the variable is not changing. How would you do this best in javascript?

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

Some mock up code (probably has syntax errors ):

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

推荐答案

例如,如果顶部和底部分别为400和600,则可以通过一些简单的数学运算基于变量来计算位置.

If the top and bottom were 400 and 600 for instance, you can calculate the position based on the variable with some simple math.

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

这篇关于内插或“补间"在两个值之间(但不设置动画)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:04