我有这个脚本,用于在 1 秒后将计数器增加 1,但是当我刷新页面时,我需要记住我计数的最后一个数字。
示例:目前,我有 40。当我刷新页面时,我需要在 40 后开始计数,而不是重置为 1。这可能吗?
function animateValue(id) {
var obj = document.getElementById(id);
var current = parseInt(obj.innerHTML);
setInterval(function() {
current++;
// Update the contents of the element
obj.innerHTML = current;
}, 1000);
}
animateValue('value');Run Code Online (Sandbox Code Playgroud)
<h1>
<div id="value">1</div>
</h1>Run Code Online (Sandbox Code Playgroud)
您可以将计数器进度存储在 中localStorage,然后检索页面加载时的值并从那里开始计数:
var obj = document.getElementById("value");
let counterStorage = localStorage.getItem('counter')
if(counterStorage) obj.innerHTML = counterStorage
function animateValue(id) {
var current = parseInt(obj.innerHTML);
setInterval(function() {
current++;
localStorage.setItem('counter', current)
obj.innerHTML = current;
}, 1000);
}
animateValue('value');
Run Code Online (Sandbox Code Playgroud)