我想每分钟改变一个图像。当计算机的时钟从 8:50 移动到 8:51 然后到 8:52 一直到 8:49 我希望我的图片从 0001.jpg 到 0002.jpg 到 0003.jpg 一直到 1440。 .jpg
由于我将使用计算机的时钟,因此我对使用 JavaScript 很感兴趣。我也刚刚开始,所以完整的代码(太棒了!)可能不是我需要的。相反,我正在寻找一个开始的地方,也许还有一个前进的方向。您知道的任何在线资源也会有所帮助
我想每分钟改变一个图像。当计算机的时钟从 8:50 移动到 8:51 然后到 8:52 一直到 8:49 我希望我的图片从 0001.jpg 到 0002.jpg 到 0003.jpg 一直到 1440。 .jpg
由于我将使用计算机的时钟,因此我对使用 JavaScript 很感兴趣。我也刚刚开始,所以完整的代码(太棒了!)可能不是我需要的。相反,我正在寻找一个开始的地方,也许还有一个前进的方向。您知道的任何在线资源也会有所帮助
计算直到下一分钟开始还有多少秒,然后使用setTimeout
开始旋转图片。使用setInterval
每 60000 毫秒执行一次。
var seconds = 60 - new Date().getSeconds();
setTimeout(function(){
console.log('start');
setInterval(function(){
console.log ('iterate over pictures here');
}, 1000 * 60);
}, seconds * 1000);
您可以在此处阅读有关这两个功能的更多信息
将下面的代码放在页面的 BODY 中:
<img />
<script>
var start = new Date().getTime(),
i = 0,
//get the node of the image to change
img = document.getElementsByTagName('IMG')[0];
setInterval(function(){
//what time is now
var now = new Date().getTime();
if(now - start > 60000){
//initialize the counter
start = now;
//overlay with 0's -> substr(-4)
//rotate on 1440 with a modulo -> i++ % 1440
img.src = ('000' + (i++ % 1440 + 1)).substr(-4) + '.jpg';
}
}, 10000); //check every 10 sec
</script>
如果您从 Javascript 开始,一个很好的参考是MDC
你会想继续学习setInterval()
。
代码看起来像这样:
var counter = 1,
lastUpdate = (new Date()).getTime(),
img = document.getElementById('image'); // Assuming your HTML has an img tag
// with an id of "image"
// This function just pads your number with 0s
function pad(num) {
var padding = '',
i = 4 - num.toString().length;
while (i > 0) {
padding += '0';
i -= 1;
}
return padding + num;
}
// This function is what actually does the updating
function update() {
var now = (new Date()).getTime();
if (lastUpdate + 1000 <= now) {
lastUpdate = now;
img.src = pad(counter) + '.jpg'; // change the image
counter += 1; // increment the counter
if (counter > 1440) { // reset to 1 if we get to our last image
counter = 1;
}
}
}
// Run update every 10th of a second
setInterval(update, 100);
Mozilla 开发者中心站点有很多很棒的JavaScript和DOM参考资料。我还建议学习使用JSLint,这将有助于避免会导致头痛的愚蠢语法错误。我建议阅读 Douglas Crockford 的书JavaSript: The Good Parts和 Stoyan Stefanov 的Object-Oriented JavaScript,它们都是学习 JavaScript 的优秀书籍。
如果你想这样做绑定到计算机时钟。使用setInterval
延迟小于一秒 (<1000) 并使用 . 检查实际时间Date()
。这样您就可以根据时钟进行更改。