更新持续时间内的增量值

Increment Value over a Duration on Update

我正在尝试制作一个脚本,以便在每次 select 更改时将一个数字递增到 selected 数字。例如,如果用户 selects 30,我希望数字以每秒 30 个值的速度增加,以便在一秒内达到 30。

我不知道出了什么问题,但是当执行这个脚本时,它只在第一页加载时递增,但没有值变化。

https://jsfiddle.net/User1010/b7znc3fL/

var valueElement = document.getElementById('value');

var option = document.getElementById('option');

var start     = 0;
var end       = parseFloat(option.innerHTML);
var duration  = 1000; // In milliseconds (divide by 1000 to get seconds).
var framerate = 50;    // In milliseconds (divide by 1000 to get seconds).

var toAdd = ( ( end - start ) * framerate ) / duration;

var interval = setInterval(function() {
var currentValue = parseFloat(valueElement.innerHTML);

if (currentValue >= end) {
  clearInterval(interval);
return;
}

valueElement.innerHTML = (!isNaN(currentValue) == true ? (currentValue +   toAdd).toFixed(2) : toAdd);
 }, framerate);

看起来您只需要将更改事件处理程序绑定到您的 select/option。 参考 MDN's Event documentation 将其添加到您的脚本以处理值的更改和更新。

请注意,如果您想使用像 jQuery 这样的框架,可以大大简化流程和脚本。

您可能想多了这个任务。我还发现控制台和 JSFiddle 中存在错误和需要更改的内容。例如,没有名称选项的元素。

https://www.khanacademy.org/computing/computer-programming/html-css-js/html-js-dom-animation/p/animating-dom-with-setinterval https://www.khanacademy.org/computer-programming/spin-off-of-challenge-stopwatch/6144204027232256

让我们从一些基本的东西开始:秒表

  1. 定义变量是为了更方便,为了更好,更常见的做法,为了更高的效率
    • 可以调用的变量 counterEl 使用 ID 'daily' 上的 document.getElementById() 初始化 span 元素。
    • 可以调用的变量 selectEl 使用 ID 'value' 上的 document.getElementById() 初始化 select 元素。
    • 可以调用 currentTime 的类型空变量,通过在 countEl.textContent 上调用 parseFloat()counterEl 转换为 float 数据类型。
    • 一个名为 stopwatch 的类型空变量,将在您使用 setInterval 时初始化。

I also used the linking Stack Overflow question for help

  1. 为 select 元素添加一个事件侦听器,每次它的值发生变化时,如下所示:selectElement.addEventListener("change", myFunction);

  2. 创建全局函数resetStopwatch() {}

    • countEl.textContent 设置为 0。
    • 为了更好的衡量,将 currentTime 也设置为 0。
    • stopwatch = window.setInterval(countUp, 1000);
  3. 创建全局 countUp 函数

这里的一切都在评论中解释。

// Turns the value into a float so it can be incremented and compared (textContent is a string)
currentTime = parseFloat(seconds.textContent);
// Add 1 second every time function is called
seconds.textContent = currentTime + 1;
if (seconds.textContent >= selectElement.value) {
window.clearInterval(stopwatch); // Stops the stopwatch if the  seconds 
reached the selected option 
console.log("My time has been cleared");
}

现在让我们稍微调整一下,使其成为 'reverse stopwatch'

setInterval 中,您希望它在一秒钟内递增那么多,因此您可以将调用更改为

 stopwatch = window.setInterval(countUp, 1000/incrementRate.value);

使用 my JS Fiddle 指导解决您的问题: https://jsfiddle.net/404_Error/z0t4spob/